Python: Difference between from .. import .. and import

Whenever we want use a function from a python module we should import it. Import can be done using one of the available options.

  1. import <ModuleName>
  2. from <ModuleName> import <FunctionName/*>

1. import statement makes the module available in the current program/namespace. To access any definitions/functions inside the module we need to use the module name reference.

Example :

  • import Test
  • Test.abc()

In the above example I wanted to use a function of the module Test, I have imported the module Test and then called the function of the module using the reference of the module name.

2. from … import … allows to direcly refer a definition from within a module. Here we don’t need to use the dot notation for accessing a definition of the module.

Example :

  • from Test import abc
  • abc()

In the above example I wanted to use a function of the module Test, I have imported the function abc() directly from the module Test. Now i can use the function without reference to the module but i will not have access to any other definitions of the module in the current namespace.

The problem with the second approach is that if we have a variable with the same name as the import definition then the one(either import of local variable) declared later will hide the other.

Example:

  • exit = 10
  • from sys import * # hides my exit variable.

 

  • from sys import *
  • exit = 10 # now hides the sys.exit function so I can’t use it.

Using the module name again and again to access the module definitions can be tedious thus it always good to alias the module.

Example:

  • import Test as t
  • t.abc()

 

I hope this post helps, please comment below with your remarks.

Leave a Reply

Your email address will not be published. Required fields are marked *