Python Modules And Packages

Modules and Packages in Python

Code organization :

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:

Modules and Packages in Python

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:

Method 1:

CODE/PROGRAM/EXAMPLE
from Flights import ManageFlights 
	#from packagename import modulename
	ManageFlights.add(10)

Method 2:

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:

(i)

CODE/PROGRAM/EXAMPLE
import Flights.Manage
	import Employees.Manage
	Flights.Manage.add()
	Employees.Manage.add()

(ii)

CODE/PROGRAM/EXAMPLE
from Flights import Manage as FManage
	from Employees import Manage as EManage
	FManage.add()
	EManage.add()

(iii)

CODE/PROGRAM/EXAMPLE
from Flights.Manage import add as add1
	from Employees.Manage import add as add2
	add1()
	add2()
#modules_and_packages_in_python #python_packages #python_xlrd #python_packages_list #python_libraries_list #python_libraries_for_data_science #python_modules_and_packages #python_import_package

(New page will open, for Comment)

Not yet commented...