Python import statement is used to import modules that we want to use in our program. Python modules are python scripts containing utility functions, types, classes etc. There are many modules that we use regularly in python programs such as sys, os, collections etc.
Table of Contents
If we want to import python built-in modules or any third party module installed using a package manager such as PIP, then we can very easily import and use them in our program.
Copyimport collections import sys
Python looks for modules and packages into
sys.path property. This path always contains the current directory from where the script is executed, so any module in the current directory can be imported as is.
Python imports are case sensitive, so
import sys and
import Sys are looking for different modules to import.
Python looks for a module into the built-in modules first. If not found, then it searches for modules in the current directory. So if we have
math.py file in the same directory as our main script, then it will be loaded when
import math is called if ‘math’ module is not in the built-in modules. You can get a list of built-in modules using
sys.builtin_module_names. Below image shows the built-in modules in my python installation.
Python import class/functions from module
We can import specific classes from module too. This way we can import specific parts of a module and use it. This also helps in writing fluent code. We can achieve this using from keyword with the import statement.
Copyfrom collections import namedtuple from os import path
Python import user-defined module
When we create a python script, we can import it into another python script using its name. Let’s say we have following directory structure with multiple python scripts.
We have following functions defined in
Copydef add(i, j): return int(i) + int(j) def uppercase(s): return str(s).upper()
We can import it into
python_import_examples.py and use its functions.
Copyimport utils print(utils.add(10,10)) print(utils.uppercase('java'))
Python import as
We can define our own name for the imported module using
import as statement.
Copy# python import as import utils as u print(u.add(10,10)) print(u.uppercase('java'))
The result will be the same as the earlier program.
Python import from another directory
If the python script we are importing is in the same directory, then we can import is easily just like built-in modules. However, if the python script is present in another directory, then we can use
importlib library to import them as a module.
Let’s say our
strutils.py has following functions:
Copydef uppercase(s): return str(s).upper() def lowercase(s): return str(s).lower()
Now let’s see how to use importlib to import this python script into our example.
Copy# Refer: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly # Refer: https://stackoverflow.com/questions/4383571/importing-files-from-different-folder import importlib, importlib.util def module_from_file(module_name, file_path): spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module strutils = module_from_file("strutils", "../mymodule/strutils.py") print(strutils.uppercase('java')) print(strutils.lowercase('DATA'))
Python import class from another file
We can import scripts and use the classes defined in them using importlib too. Let’s say we have classes
Student defined in
Copyclass Person: name = "" def __init__(self, personName): self.name = personName def showName(self): print(self.name) class Student(Person): id = 0 def __init__(self, studentName, studentId): Person.__init__(self, studentName) self.id = studentId def getId(self): return self.id
Here is the example code where I am using the earlier defined function to import this script and use its classes.
Copy#python import class from another file mc = module_from_file("myclasses", "../mymodule/myclasses.py") p = mc.Person('Pankaj') p.showName() s = mc.Student('David',25) s.showName() print(s.getId())
Notice that we can keep any name for the module we are importing, it’s similar to using
import as statement.
There is another way to import scripts from another directory using the
Copyimport sys sys.path.append("../mymodule/") from myclasses import Person as PC p = PC('Meghna') p.showName()
This is useful when we want to import only specific classes and functions from the imported file. Also, using this code is much easier to understand.
Python import statement allows us to import modules, python scripts, specific classes and functions from modules. It’s very easy to use and since most of the times we work on built-in modules or modules installed using PIP, we don’t need to write logic to load scripts from another directory.
Reference: Official Documentation