Import Module in Python With Examples
Import Module in Python With Examples
Import Module in Python With Examples
Here is the flow to create and import the module as shown in the screenshot:
(//cdn.guru99.com/images/2/062620_0700_Importmodul1.png)
modtest/
test.py
display.py
Def display_message():
import test
While importing, you don't have to mention the test.py but just the name of the file.
Step5)
Then you can call the function display_message() from test.py inside display.py, you need to
make use of module_name.function_name.
Import test
print(test.display_message())
Step 6)
When you execute display.py, you will get the following output:
myproj/
Car.py
display.py
Filename : Car.py
class Car:
brand_name = "BMW"
model = "Z4"
manu_year = "2020"
self.brand_name = brand_name
self.model = model
self.manu_year = manu_year
def car_details(self):
def get_Car_brand(self):
def get_Car_model(self):
In the file Car.py , there are attributes brand_name, model and manu_year. The functions
defined inside the class are car_details(), get_Car_brand(), get_Car_model().
Let us now use the file Car.py as a module in another file called display.py.
Filename : display.py
import Car
print(car_det.brand_name)
print(car_det.car_details())
print(car_det.get_Car_brand())
print(car_det.get_Car_model())
Output:
BMW
Car model is Z5
Car model is Z5
So we can access all the variables and functions from Car.py using Car module.
When you want only specific things to be imported, you can make use of "from" keyword to
import what you want.
So the syntax is
modtest/
test.py
display.py
Filename : test.py
defdisplay_message():
def display_message1():
Now you want display_message() function. The function or variable that you are importing
can be directly accessed as shown below:
File Name : display.py
print(display_message())
Output:
Now if you happen to use the function display_message1() ,it will throw an error that the
function is not defined as shown below:
print(display_message1())
Output:
print(display_message1())
Syntax:
Import module
Or by using
test.py
display.py
my_name = "Guru99"
my_address = "Mumbai"
defdisplay_message():
def display_message1():
Example
Filename : display.py
Import test
print(test.display_message())
print(test.display_message1())
print(test.my_name)
print(test.my_address)
The module name test is used to refer to the function and variables inside module test.
Output:
Guru99
Mumbai
Using import *
Let us see an example using import *. Using import *, the functions and variables are
directly accessible, as shown in the example below:
print(display_message())
print(display_message1())
print(my_name)
print(my_address)
Output:
Guru99
Mumbai
So when dir() is used on the module, it will give you the variables, functions that are present
inside the module.
Here is a working example of dir() on a module. We have a class called Car.py, let us import
Car and assign to dir() to see the output.
Car.py
test.py
Filename: Car.py
class Car:
brand_name = "BMW"
model = "Z4"
manu_year = "2020"
self.brand_name = brand_name
self.model = model
self.manu_year = manu_year
def car_details(self):
def get_Car_brand(self):
def get_Car_model(self):
Filename: test.py
import Car
class_contents = dir(Car)
print(class_contents)
The output gives us the name of the class and all the functions defined in Car.py.
You can also try using dir() on a built-in module available in Python. Let us try the same on
json module as shown in the example below. It will display all the properties and methods
available in json module.
Import json
json_details = dir(json)
print(json_details)
Output:
Packages
A package is a directory with all modules defined inside it. To make a Python interpreter
treat it as a package, your directory should have the init.pyfile. The init.py makes the
directory as a package. Here is the layout of the package that we are going to work on.
(//cdn.guru99.com/images/2/062620_0700_Importmodul2.png)
The name of the package is my package. To start working with the package, create a
directory called package/. Inside the directory, create an empty file called __init__.py.
Create 3 more files module1.py, module2.py, and module3.py and define the functions as
shown in the screenshot. Here are the details of module1.py,module2.py and module3.py
module1.py
def mod1_func1():
def mod1_func2():
def mod1_func3():
module2.py
def mod2_func1():
def mod2_func2():
def mod2_func3():
module3.py
def mod3_func1():
def mod3_func2():
def mod3_func3():
The packages ready for use. Now call the package inside any of your file as shown below
:test.py:
Here, the mypackage.module1 is imported and given an alias name as mod1. Similarly, you
can use other modules module2.py and module3.py from my package.
print(mod1.mod1_func1())
print(mod1.mod1_func2())
print(mod1.mod1_func2())
Output:
None
None
None
We have just demonstrated the package with a simple module with functions inside it. As
per your project, you can also package with have sub-packages. Sub-folders/ having
modules with classes defined.
To sum up, the interpreter does the following search to locate the module:
You can get the details of sys.path by importing sys module and print the sys.path. It will
give you the list of directories as shown below:
importsys
print(sys.path)
Output:
\Python37\\python37.zip', 'Users\\AppData\\Local\\Programs\\Python\\P
ython37\\DLLs']
You can also modify the path and keep the directories as per your requirements.
Syntax:
Mod test/
test.py
display.py
my_name = "Guru99"
my_address = "Mumbai"
def display_message():
def display_message1():
Import test as t
print(t.display_message())
print(t.display_message1())
print(t.my_name)
print(t.my_address)
The alias that is used for test module is t . So the function and variables from test.py can be
referred using the alias t.
Output:
Guru99
Mumbai
(//cdn.guru99.com/images/2/062620_0700_Importmodul3.png)
The root folder is my project/. It has two subfolders package1 and package2.
The folder package2 has one class myclass.py, a sub-package subpkg with module3.py, and
last module4.py.
Let us now see how to make use of absolute imports to refer to the functions present in each
of the module.
To work with the functionmyfunc1, you will need to import as follows:
or
module1.myfunc1()
To work with the function myfunc3 you will need to import as follows:
or
module3.myfunc3()
Disadvantages:
The import path can get very long in-case, the modules are nested, and if the name of
the modules is lengthy.
In relative import, the module to be imported is relative to the current location that is the
location where the import statement is present.
Syntax:
In relative imports, you need to add a period (.) before the module name when importing
using from.
It will be 2 periods (..) before the module name if the module is in the one level up from the
current location.
Referring to the folder structure figure mentioned above, we have the following modules
with their function, which we need to refer to.
To work with the function myfunc3, you will need to import as follows:
Using relative imports, it is difficult to trace back where the code resides
Summary:
Import in Python helps you to refer to the code, i.e., .functions/objects that are written in
another file. It is also used to import python libraries/packages that are installed using
pip(python package manager), and you need then to use in your code.
Import functionality is available in other languages like typescript, JavaScript, java, ruby,
etc.
A module is python is the code written inside the file, for example (test.py). Inside your
file, you can have your variables, functions, or your class defined. The entire file becomes
a module and can be imported inside another file to refer to the code.
With module functionality, you can break your code into different files instead of writing
everything inside one file. Later, using import, you can refer to the code inside the file
you need.
Python has its built-in modules, and also external libraries/packages installed using a
python package manager (pip), e.g., pandas, NumPy, etc. are referred to as modules.
You can import only a small part of the module, i.e., only the required functions and
variable names from the module instead of importing full code.
You can also convert the module name to a shorter form by giving an alias name to it.
The alias can be done using the keyword.
A package is a directory with all modules defined inside it. To make a Python interpreter
treat it as a package, your directory should have the __init.pyfile. The init.py makes the
directory as a package. Here is the layout of the package that we are going to work on.
During execution, when python comes across import module name, the interpreter tries
to locate the module. It searches the module in the build-in module list. Later in all, the
directories defined inside sys.path.
For Absolute imports, you need to add the entire path of your module right from the
project root folder.
In relative import, the module to be imported is relative to the current location that is the
location where the import statement is present.
Next (/web-scraping-tools.html)
(https://www.facebook.com/guru99com/)
(https://twitter.com/guru99com)
(https://www.linkedin.com/company/guru99/)
(https://www.youtube.com/channel/UC19i1XD6k88KqHlET8atqFQ)
(https://forms.aweber.com/form/46/724807646.htm)
About
About Us (/about-us.html)
Contact Us (/contact-us.html)
Career Suggestion
SAP Career Suggestion Tool (/best-sap-module.html)
Interesting
eBook (/ebook-pdf.html)
Blog (/blog/)
Quiz (/tests.html)
Execute online
Execute Java Online (/try-java-editor.html)