Python Modules And Packages
Modules and Packages in Python
Code organization is done through modules and packages! A Module is a python file with a .py extension. A package is a folder which contains an file whose name is __init__.py. Package can store many python modules/files in it.
Sample python project structure:
Packages
Let's assume that the ManageFlights.py inside Flights package has the below code:
CODE/PROGRAM/EXAMPLE
airline="Smart Airlines"
def add(no_of_flights):
print(no_of_flights," flights added to the fleet")
If we need to access the function add(), inside the ManageFlights module in some other module, then we can import the ManageFlights module and use it.
Import can be done in two ways:
CODE/PROGRAM/EXAMPLE
from Flights import ManageFlights
#from packagename import modulename
ManageFlights.add(10)
CODE/PROGRAM/EXAMPLE
import Flights.ManageFlights
#import packagename.modulename
Flights.ManageFlights.add(10)
Packages Naming conflict :
Consider a scenario where 2 modules have the same name which are present in different package and both of them have the same function ‘add’.
Syntax
Flights->Manage.py->add()
Employees->Manage.py->add()
To avoid naming conflicts during import we can use one of the below techniques:
CODE/PROGRAM/EXAMPLE
import Flights.Manage
import Employees.Manage
Flights.Manage.add()
Employees.Manage.add()
CODE/PROGRAM/EXAMPLE
from Flights import Manage as FManage
from Employees import Manage as EManage
FManage.add()
EManage.add()
CODE/PROGRAM/EXAMPLE
from Flights.Manage import add as add1
from Employees.Manage import add as add2
add1()
add2()