SlideShare a Scribd company logo
1 of 29
Modules and Packages
in Python
Dr.T.Maragatham
Kongu Engineering College, Perundurai
Modules
• Modules - a module is a piece of software
that has a specific functionality. Each module
is a different file, which can be edited
separately.
• Modules provide a means of collecting sets of
Functions together so that they can be used
by any number of programs.
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Packages
• Packages – sets of modules that are grouped
together, usually because their modules
provide related functionality or because they
depend on each other.
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Modules
• programs are designed to be run, whereas
modules are designed to be imported and
used by programs.
• Several syntaxes can be used when importing.
For example:
• import importable
• import importable1, importable2, ...,
importableN
• import importable as preferred_name
Dr.T.Maragatham Kongu Engineering
College, Perundurai
• make the imported objects (variables, functions,
data types, or modules) directly accessible.
• from …import syntax to import lots of objects.
• Here are some other import syntaxes:
• from importable import object as preferred_name
• from importable import object1, object2, ...,
objectN
• from importable import (object1, object2,
object3, object4, object5, object6, ..., objectN)
• from importable import *
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Python import statement
• We can import a module using
the import statement and access the
definitions inside it using the dot operator.
• import math
• print("The value of pi is", math.pi)
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Import with renaming
• We can import a module by renaming it as
follows:
• # import module by renaming it
• import math as m
• print("The value of pi is", m.pi)
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Python from...import statement
• We can import specific names from a module
without importing the module as a whole.
Here is an example.
• # import only pi from math module
• from math import pi
• print("The value of pi is", pi)
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Import all names
• We can import all names(definitions) from a
module using the following construct:
• from math import *
• print("The value of pi is", pi)
Dr.T.Maragatham Kongu Engineering
College, Perundurai
The dir() built-in function
• We can use the dir() function to find out names that
are defined inside a module.
• we have defined a function add() in the
module example that we had in the beginning.
• dir(example)
• ['__builtins__', '__cached__', '__doc__', '__file__',
'__initializing__', '__loader__', '__name__',
'__package__', 'add']
• a sorted list of names (along with add).
• All other names that begin with an underscore are
default Python attributes associated with the module
(not-user-defined).
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Let us create a module
• Type the following and save it as example.py.
• # Python Module example
• def add(a, b):
– """This program adds two numbers and return the
result"""
– result = a + b
– return result
Dr.T.Maragatham Kongu Engineering
College, Perundurai
How to import modules in Python?
import example
example.add(4,5.5)
9.5 # Answer
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Variables in Module
• The module can contain functions, as already
described, but also variables of all types
(arrays, dictionaries, objects etc):
• Save this code in the file mymodule.py
• person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Dr.T.Maragatham Kongu Engineering
College, Perundurai
• Import the module named mymodule, and
access the person1 dictionary:
• import mymodule
a = mymodule.person1["age"]
print(a)
• Run Example  36
•
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Built-in Modules
• Import and use the platform module:
• import platform
x = platform.system()
print(x)
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Import From Module
• The module named mymodule has one function and one dictionary:
• def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
• Example
• Import only the person1 dictionary from the module:
• from mymodule import person1
print (person1["age"])
Dr.T.Maragatham Kongu Engineering
College, Perundurai
• def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
• Example
• Import all objecs from the module:
• from mymodule import *
print(greeting(“Hello”)
print (person1["age"])
Dr.T.Maragatham Kongu Engineering
College, Perundurai
What are packages?
• We don't usually store all of our files on our
computer in the same location.
• We use a well-organized hierarchy of
directories for easier access.
• Similar files are kept in the same directory, for
example, we may keep all the songs in the
"music" directory.
• similar to this, Python has packages for
directories and modules for files
Dr.T.Maragatham Kongu Engineering
College, Perundurai
• As our application program grows larger in
size with a lot of modules, we place similar
modules in one package and different
modules in different packages.
• This makes a project (program) easy to
manage and conceptually clear.
• Similarly, as a directory can contain
subdirectories and files, a Python package
can have sub-packages and modules.
Dr.T.Maragatham Kongu Engineering
College, Perundurai
A Simple Example
Dr.T.Maragatham Kongu Engineering
College, Perundurai
• First of all, we need a directory. The name of this
directory will be the name of the package, which
we want to create.
• We will call our package "simple_package". This
directory needs to contain a file with the
name __init__.py.
• This file can be empty, or it can contain valid
Python code.
• This code will be executed when a package is
imported, so it can be used to initialize a
package.
• We create two simple files a.py and b.py just for
the sake of filling the package with modules
Dr.T.Maragatham Kongu Engineering
College, Perundurai
__init__.py
• A directory must contain a file
named __init__.py in order for Python to
consider it as a package.
• This file can be left empty but we generally
place the initialization code for that package in
this file
Dr.T.Maragatham Kongu Engineering
College, Perundurai
My Documents
My_Package
__init__.py First.py Second.py
Package
Main.py
Dr.T.Maragatham Kongu Engineering
College, Perundurai
• First.py
def one():
print(“First Module”)
return
• Second.py
def second():
print(“Second Module”)
return
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Main.py
• from My-Package import First
• First.one()
• from My-Package import First,Second
• First.one()
• Second.second()
Dr.T.Maragatham Kongu Engineering
College, Perundurai
Dr.T.Maragatham Kongu Engineering
College, Perundurai
• For example, if we want to import
the start module in the above example, it can
be done as follows:
• import Game.Level.start
• Now, if this module contains
a function named select_difficulty(), we must
use the full name to reference it.
• Game.Level.start.select_difficulty(2)
Dr.T.Maragatham Kongu Engineering
College, Perundurai
• If this construct seems lengthy, we can import
the module without the package prefix as
follows:
• from Game.Level import start
• We can now call the function simply as
follows:
• start.select_difficulty(2)
Dr.T.Maragatham Kongu Engineering
College, Perundurai
• Another way of importing just the required
function (or class or variable) from a module
within a package would be as follows:
• from Game.Level.start import select_difficulty
Now we can directly call this function.
• select_difficulty(2)
Dr.T.Maragatham Kongu Engineering
College, Perundurai

More Related Content

What's hot

File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in pythonSantosh Verma
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentationVedaGayathri1
 
Data types in python
Data types in pythonData types in python
Data types in pythonRaginiJain21
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in pythonhydpy
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptxAkshayAggarwal79
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Edureka!
 
Modules in Python Programming
Modules in Python ProgrammingModules in Python Programming
Modules in Python Programmingsambitmandal
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 

What's hot (20)

Python Functions
Python   FunctionsPython   Functions
Python Functions
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Python list
Python listPython list
Python list
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
 
Modules in Python Programming
Modules in Python ProgrammingModules in Python Programming
Modules in Python Programming
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
Python-Polymorphism.pptx
Python-Polymorphism.pptxPython-Polymorphism.pptx
Python-Polymorphism.pptx
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 

Similar to Modules and packages in python

package module in the python environement.pptx
package module in the python environement.pptxpackage module in the python environement.pptx
package module in the python environement.pptxMuhammadAbdullah311866
 
Modules 101
Modules 101Modules 101
Modules 101gjcross
 
Python Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptxPython Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptxSingamvineela
 
Python import mechanism
Python import mechanismPython import mechanism
Python import mechanismYuki Nishiwaki
 
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptxkrushnaraj1
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++jehan1987
 
Using Python Libraries.pdf
Using Python Libraries.pdfUsing Python Libraries.pdf
Using Python Libraries.pdfSoumyadityaDey
 
Modules and Packages in Python Programming Language.pptx
Modules and Packages in Python Programming Language.pptxModules and Packages in Python Programming Language.pptx
Modules and Packages in Python Programming Language.pptxarunavamukherjee9999
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxRohitKumar639388
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part IIIHari Christian
 
jb_Modules_in_Python.ppt
jb_Modules_in_Python.pptjb_Modules_in_Python.ppt
jb_Modules_in_Python.pptloliktry
 
Module Structure in Odoo 16
Module Structure in Odoo 16Module Structure in Odoo 16
Module Structure in Odoo 16Celine George
 

Similar to Modules and packages in python (20)

package module in the python environement.pptx
package module in the python environement.pptxpackage module in the python environement.pptx
package module in the python environement.pptx
 
Python libraries
Python librariesPython libraries
Python libraries
 
Namespaces
NamespacesNamespaces
Namespaces
 
Modules 101
Modules 101Modules 101
Modules 101
 
Python Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptxPython Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptx
 
Python import mechanism
Python import mechanismPython import mechanism
Python import mechanism
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptx
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
 
Using Python Libraries.pdf
Using Python Libraries.pdfUsing Python Libraries.pdf
Using Python Libraries.pdf
 
Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
 
Python modules
Python modulesPython modules
Python modules
 
Modules and Packages in Python Programming Language.pptx
Modules and Packages in Python Programming Language.pptxModules and Packages in Python Programming Language.pptx
Modules and Packages in Python Programming Language.pptx
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
 
Python training
Python trainingPython training
Python training
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
 
jb_Modules_in_Python.ppt
jb_Modules_in_Python.pptjb_Modules_in_Python.ppt
jb_Modules_in_Python.ppt
 
Module Structure in Odoo 16
Module Structure in Odoo 16Module Structure in Odoo 16
Module Structure in Odoo 16
 
Python Crawler
Python CrawlerPython Crawler
Python Crawler
 

Recently uploaded

Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...gragchanchal546
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...ppkakm
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...Amil baba
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementDr. Deepak Mudgal
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptxrouholahahmadi9876
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...ronahami
 
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...vershagrag
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxNANDHAKUMARA10
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 

Recently uploaded (20)

Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...
 
Signal Processing and Linear System Analysis
Signal Processing and Linear System AnalysisSignal Processing and Linear System Analysis
Signal Processing and Linear System Analysis
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
 
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptx
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 

Modules and packages in python

  • 1. Modules and Packages in Python Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 2. Modules • Modules - a module is a piece of software that has a specific functionality. Each module is a different file, which can be edited separately. • Modules provide a means of collecting sets of Functions together so that they can be used by any number of programs. Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 3. Packages • Packages – sets of modules that are grouped together, usually because their modules provide related functionality or because they depend on each other. Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 4. Modules • programs are designed to be run, whereas modules are designed to be imported and used by programs. • Several syntaxes can be used when importing. For example: • import importable • import importable1, importable2, ..., importableN • import importable as preferred_name Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 5. • make the imported objects (variables, functions, data types, or modules) directly accessible. • from …import syntax to import lots of objects. • Here are some other import syntaxes: • from importable import object as preferred_name • from importable import object1, object2, ..., objectN • from importable import (object1, object2, object3, object4, object5, object6, ..., objectN) • from importable import * Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 6. Python import statement • We can import a module using the import statement and access the definitions inside it using the dot operator. • import math • print("The value of pi is", math.pi) Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 7. Import with renaming • We can import a module by renaming it as follows: • # import module by renaming it • import math as m • print("The value of pi is", m.pi) Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 8. Python from...import statement • We can import specific names from a module without importing the module as a whole. Here is an example. • # import only pi from math module • from math import pi • print("The value of pi is", pi) Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 9. Import all names • We can import all names(definitions) from a module using the following construct: • from math import * • print("The value of pi is", pi) Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 10. The dir() built-in function • We can use the dir() function to find out names that are defined inside a module. • we have defined a function add() in the module example that we had in the beginning. • dir(example) • ['__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', 'add'] • a sorted list of names (along with add). • All other names that begin with an underscore are default Python attributes associated with the module (not-user-defined). Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 11. Let us create a module • Type the following and save it as example.py. • # Python Module example • def add(a, b): – """This program adds two numbers and return the result""" – result = a + b – return result Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 12. How to import modules in Python? import example example.add(4,5.5) 9.5 # Answer Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 13. Variables in Module • The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc): • Save this code in the file mymodule.py • person1 = { "name": "John", "age": 36, "country": "Norway" } Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 14. • Import the module named mymodule, and access the person1 dictionary: • import mymodule a = mymodule.person1["age"] print(a) • Run Example  36 • Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 15. Built-in Modules • Import and use the platform module: • import platform x = platform.system() print(x) Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 16. Import From Module • The module named mymodule has one function and one dictionary: • def greeting(name): print("Hello, " + name) person1 = { "name": "John", "age": 36, "country": "Norway" } • Example • Import only the person1 dictionary from the module: • from mymodule import person1 print (person1["age"]) Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 17. • def greeting(name): print("Hello, " + name) person1 = { "name": "John", "age": 36, "country": "Norway" } • Example • Import all objecs from the module: • from mymodule import * print(greeting(“Hello”) print (person1["age"]) Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 18. What are packages? • We don't usually store all of our files on our computer in the same location. • We use a well-organized hierarchy of directories for easier access. • Similar files are kept in the same directory, for example, we may keep all the songs in the "music" directory. • similar to this, Python has packages for directories and modules for files Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 19. • As our application program grows larger in size with a lot of modules, we place similar modules in one package and different modules in different packages. • This makes a project (program) easy to manage and conceptually clear. • Similarly, as a directory can contain subdirectories and files, a Python package can have sub-packages and modules. Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 20. A Simple Example Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 21. • First of all, we need a directory. The name of this directory will be the name of the package, which we want to create. • We will call our package "simple_package". This directory needs to contain a file with the name __init__.py. • This file can be empty, or it can contain valid Python code. • This code will be executed when a package is imported, so it can be used to initialize a package. • We create two simple files a.py and b.py just for the sake of filling the package with modules Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 22. __init__.py • A directory must contain a file named __init__.py in order for Python to consider it as a package. • This file can be left empty but we generally place the initialization code for that package in this file Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 23. My Documents My_Package __init__.py First.py Second.py Package Main.py Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 24. • First.py def one(): print(“First Module”) return • Second.py def second(): print(“Second Module”) return Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 25. Main.py • from My-Package import First • First.one() • from My-Package import First,Second • First.one() • Second.second() Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 27. • For example, if we want to import the start module in the above example, it can be done as follows: • import Game.Level.start • Now, if this module contains a function named select_difficulty(), we must use the full name to reference it. • Game.Level.start.select_difficulty(2) Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 28. • If this construct seems lengthy, we can import the module without the package prefix as follows: • from Game.Level import start • We can now call the function simply as follows: • start.select_difficulty(2) Dr.T.Maragatham Kongu Engineering College, Perundurai
  • 29. • Another way of importing just the required function (or class or variable) from a module within a package would be as follows: • from Game.Level.start import select_difficulty Now we can directly call this function. • select_difficulty(2) Dr.T.Maragatham Kongu Engineering College, Perundurai