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

Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 

What's hot (20)

Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
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...
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Python libraries
Python librariesPython libraries
Python libraries
 
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 strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 

Similar to Modules and packages in python

jb_Modules_in_Python.ppt
jb_Modules_in_Python.pptjb_Modules_in_Python.ppt
jb_Modules_in_Python.ppt
loliktry
 

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
 
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 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
 
Python for Beginners
Python  for BeginnersPython  for Beginners
Python for Beginners
 
Composition of a Module in Odoo 16
Composition of a Module in Odoo 16Composition of a Module in Odoo 16
Composition of a Module in Odoo 16
 

Recently uploaded

result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
rknatarajan
 

Recently uploaded (20)

Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 

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