Importing Modules in Python

Let’s learn about the different ways to import modules in python.

Photo by Tom Fisk from Pexels

Importing Modules in Python

Modules

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Modules provide the reusability of code. By using modules, we can group related code.

Topics covered in this story

  1. Different ways to import module.
  • Using the import statement
  • Using from clause
  • Using from clause and *

2. The module search path

3. Errors Raised

  • ModuleNotFoundError
  • AttributeError
  • ImportError
  • NameError

Different ways to import module.

  1. Using the import statement

import modulename

The import statement is executed in two steps:

  1. find a module, loading and initializing it if necessary
  2. define a name or names in the local namespace for the scope where the import statement occurs.

The imported module names are placed in the importing module’s global symbol table. Only the module name is placed and not the function, variable, or class name in module. So, if we want to access the functions or variables from the module imported, have to do by mentioning 
modname.fnname -For accessing functions
modname.varname -For accessing variables

Example:

  • I have created a file “add.py”.It contains variables a,b, and functiona1.
x=5
y=10
def a1(a,b):
return (a+b)
  • Now, have to import this module in another file “calc.py”

The imported module name (add.py)only placed in the importing module’s (calc.py) global symbol table.

import add →Imported add and bounded locally

So, accessing function a1 as
add.a1()

Accessing variables like
add.x
add.y

import add
print (add.a1(4,5))
#Output:9

print (add.x)#Output:5
print (add.y)#Output:10

Assign a local name

We can assign a local name for modules imported or modname.fnname and use it in the program

Giving local name for an imported module like

import add as a

import add as a → Imported add and bounded as a

Example:

We can use that local name to refer the imported module in this program

import add as a
print (a.a1(4,5))
#Output:9

print (a.x)#Output:5

Giving local name for modname.fnname like

b=add.a1

We can use that local name to access the function from the imported module.

import add
n=add.a1
print (n(3,4))
#Output:7

2. Using from clause

from modname import fn1,fn2,var1

  1. First, it will find the module specified in the from clause, loading, and initializing it if necessary.
  2. For each of the identifiers specified in the import clauses
    * check if the imported module has an attribute by that name
    * if not, attempt to import a submodule with that name and then check the imported module again for that attribute
    * if the attribute is not found, ImportError is raised.
    * otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

Example

This import statement imports names from the module directly into the importing module’s symbol table.

So we can access functions and variables directly without mentioning the module name.

from add import a1 ,x→ Imported add and add.a1 bounded as a1,add.x bounded as x

from add import a1,x
print (a1(2,3))#Output:5
print (x)#Output:5

3. Using from clause and *

It will import all names that the module defines. We can access all the names in the imported module directly.

from add import *
print (a1(2,3))#Output:5
print (x)#Output:5

Note: This imports all names except those beginning with an underscore (_). In most cases Python programmers do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some things you have already defined.


The module search path

When a module is first imported

  1. The interpreter first searches for a built-in module
  2. Then it will search for that file in the list of directories given by the variable sys.path.

sys.path is initialized from these locations

  1. The current directory (the directory containing the input script)
  2. PYTHONPATH -Environmental variable with the list of directories
  3. Installation dependent directory
import sys
print (sys.path)

It will list all the module search path

If we want to add any directory to be included in that search path, we can add by using sys.path.append()

import sys
sys.path.append("C:indhuProject")

Now, the imported modules will be searched in this path too. Like this, we can import modules from a different directory also.


Errors Raised

  1. ModuleNotFoundError
  2. AttributeError
  3. ImportError
  4. NameError

1.ModuleNotFoundError

If the module imported doesn’t exist means it will raise ModuleNotFoundError

Example 1

from sub import a1,x
print (x)
#Output:ModuleNotFoundError: No module named 'sub'

Example 2

import sub
print (x)
#Output:ModuleNotFoundError: No module named 'sub'

2. AttributeError

While accessing function/variables from the imported module and if it doesn’t exist means, it will raise AttributeError.

import add
print (add.a2(1,2))
#Output:AttributeError: module 'add' has no attribute 'a2'

3.ImportError

Using from clause, when we are importing, if the attributes are not available means it will raise ImportError

from add import s2,x
print (x)
#Output:ImportError: cannot import name 's2' from 'add'

4.NameError

If we use the import statement and if we access the function name and variable name directly, it will raise NameError.

We should access like modname.varname

Example 1:

import add
print (a1(4,5))
#Output:NameError: name 'a1' is not defined
print (x)#Output:NameError: name 'x' is not defined

Example 2:

If we create a local name for modules, then we have to use that local name only to refer that imported module. Else it will raise NameError

import add as a
print (add.x)
#Output:NameError: name 'add' is not defined

Example 3:

If we import using from clause, it will imports names from the module directly into the importing module’s symbol table. So we can access the function name/variable name mentioned in the import statement directly.

If we mention modname.fnname() , it will raise NameError.

from add import a1
print (add.a1(3,4))
#Output:NameError: name 'add' is not defined

Conclusion:

The import statement will look for modules in the path mentioned by sys.path. If we want to import from any other path, include that path in sys.path by using the command sys.path.append()

import add →Imported add and bounded locally
import add as a → Imported add and bounded as a
from add import a1,x→ Imported add and add.a1 bounded as a1,add.x bounded as x

I hope that you have found this article helpful, thanks for reading!

Resources(Python Documentation):

Modules

import statement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s