Python import
In this article, we will understand how to import classes from another file in python. We will also take a look at importing classes from another file in another directory.
Importing a class means using it in another file. This promotes code reusability.
Classes can be imported using python
import
statement. Its syntax is import moduleName
where moduleName is the name of a python module that you want to import
When importing classes, the syntax of import becomes
from fileName import className
where fileName is the name of the file from which you want to import a class, and
className is the name of the python class that needs to be imported.
Importing class from same folder
Suppose you have below folder or directory structure
main |-- human_def.py |-- run.py
where the human_def.py file contains a class. Its contents are
class Human: def name(self): return 'Alex'
Now, to use it in run.py, we need to import it as shown below
# run.py from human_def import Human # create object of class human=Human() # call class method print(human.name())
So, the syntax to import a class from same directory is,
from fileName import className
You can also assign an alias or short name to the imported class using as
keyword. The class can then be referred using this short name.
Above example can be modified to
# run.py from human_def import Human as H # refer class with short name human=H() # call class method print(human.name())
Suppose the file from in you want to import a class is not in the same directory as the file containing the class.
So, let’s say, the structure is as below
main |-- mods |-- human_def.py |-- run.py
In this case, the syntax to import class name becomes
from directory.fileName import className
For importing classes from a different directory, you need to add a file with name __init__.py
.
This file can be empty and indicates python interpreter to treat the folder as a package containing class definition files.
Python docs state,
The
__init__.py
files are required to make Python treat directories containing the file as packages.
Updated folder structure should be,
main |-- mods |-- human_def.py |-- __init__.py |-- run.py
Example to import classes from another directory is given below
# run.py from mods.human_def import Human # create object of class human=Human() # call class method print(human.name())
If the class file is further nested inside other directories, then you must provide complete path of the file with the names of directories separated by a dot(.).
Thus, for the below structure
main |-- mods |-- defs |-- human_def.py |-- __init__.py |-- run.py
Class from file human_def.py should be imported as
from mods.defs.human_def.py import Human
Note that __init__.py
should be present in the outer directory only. It is not required to be present in both the folders.
Hope the article was useful.