SlideShare a Scribd company logo
1 of 47
Modules and Packages
Damian Gordon
Modules and Packages
• As we create more and more classes we need a way to
organise them in such a way to make then available and easy
to find.
• Modules in Python are simply files, if you have two files in the
same folder we can load a class from one module for use in the
other module.
Modules and Packages
• As we create more and more classes we need a way to
organise them in such a way to make then available and easy
to find.
• Modules in Python are simply files, if you have two files in the
same folder we can load a class from one module for use in the
other module.
Modules and Packages
• So, for example, if we are building an e-Commerce system, and
we create a single file (module) that contains all the classes
and methods related to accessing the database, then as long as
all the other necessary modules (product, customer, inventory
classes) are in the same folder, those modules can use the
database module to access the database.
Modules and Packages
• So if we put our Point class in a file (module) called:
– Pointdocstrings.py
• We can create another file (module) to include that class, by
doing the following:
import Pointdocstrings
p1 = Pointdocstrings.Point()
Modules and Packages
# PROGRAM Calling-Point-Docstrings:
import Pointdocstrings
p1 = Pointdocstrings.Point()
p2 = Pointdocstrings.Point()
p1.move(2,2)
p2.move(6,5)
print("CALLING: P1-x, P1-y is: ", p1.x, p1.y)
print("CALLING: P2-x, P2-y is: ", p2.x, p2.y)
print("CALLING: Distance from P1 to P2 is:", p1.calc_distance(p2))
# END.
Modules and Packages
• When we bring Pointdocstrings into the calling
program, we say that Pointdocstrings is now part of the
calling program’s namespace (which is the list of methods and
classes available to the current program).
Modules and Packages
• If we just want to being one specific class in from a file
(module) we simple say:
from Pointdocstrings import Point
And we can declare instances as follows:
p1 = Point()
Modules and Packages
# PROGRAM Calling-Point-Docstrings:
from Pointdocstrings import Point
p1 = Point()
p2 = Point()
p1.move(2,2)
p2.move(6,5)
print("CALLING: P1-x, P1-y is: ", p1.x, p1.y)
print("CALLING: P2-x, P2-y is: ", p2.x, p2.y)
print("CALLING: Distance from P1 to P2 is:", p1.calc_distance(p2))
# END.
Modules and Packages
• If we already have a class called Point in the existing
namespace, then we can use the as clause:
from Pointdocstrings import Point as Pt
And we can declare instances as follows:
p1 = Pt()
Modules and Packages
# PROGRAM Calling-Point-Docstrings:
from Pointdocstrings import Point as Pt
p1 = Pt()
p2 = Pt()
p1.move(2,2)
p2.move(6,5)
print("CALLING: P1-x, P1-y is: ", p1.x, p1.y)
print("CALLING: P2-x, P2-y is: ", p2.x, p2.y)
print("CALLING: Distance from P1 to P2 is:", p1.calc_distance(p2))
# END.
Modules and Packages
• If we want to import more than one class we do:
from Pointdocstrings import Point, Line
But we should avoid doing this:
from Pointdocstrings import *
Organizing the Modules
Modules and Packages
• As projects get larger and larger it becomes more and more
difficult to organise all of the modules (Python files) in a single
folder.
• To help with this issue, Python allows you to organise your
modules into sub-folders (called Packages). The name of the
package is the name of the folder.
Modules and Packages
• To achieve this we place a file called _ _init_ _.py in each
sub-folder we wish to be included in the project.
parent_directory/
main.py
Drawing/
_ _init_ _.py
point-call.py
point-docstrings.py
Maths/
_ _init_ _.py
Theorem.py
Modules and Packages
• To achieve this we place a file called _ _init_ _.py in each
sub-folder we wish to be included in the project.
parent_directory/
main.py
Drawing/
_ _init_ _.py
point-call.py
point-docstrings.py
Maths/
_ _init_ _.py
Theorem.py
_ _init_ _.py
Modules and Packages
• For the moment we are going to assume that the special files,
the _ _init_ _.py is empty.
• We can import packages in two ways, using Absolute Imports
and Relative Imports.
Modules and Packages:
Absolute Imports
• An absolute import is an IMPORT where you fully specify the
location of the classes being imported.
Modules and Packages:
Absolute Imports
• We can do this in a number of ways:
import Drawing.point-call
P1 = point-call.Point()
from Drawing.point-call import Point
P1 = Point()
from Drawing import point-call
P1 = point-call.Point()
Modules and Packages:
Absolute Imports
• We can do this in a number of ways:
import Drawing.point-call
P1 = point-call.Point()
from Drawing.point-call import Point
P1 = Point()
from Drawing import point-call
P1 = point-call.Point()
PACKAGE MODULE
PACKAGE MODULE CLASS
PACKAGE MODULE
Modules and Packages:
Relative Imports
• Relative Imports specific the location of the classes to be
imported relative to the current package.
Modules and Packages:
Relative Imports
• Relative Imports specific the location of the classes to be
imported relative to the current package.
The current directory
(package)
.
The previous directory
(package)
..
Modules and Packages:
Relative Imports
Modules and Packages:
Relative Imports
If Point-call.py
wants to call
Point-docstrings.py,
you can say:
from
.Point-docstrings.py
import
Point
Modules and Packages:
Relative Imports
If Theorem.py
wants to call
Point-docstrings.py,
you can say:
from
..Point-docstrings.py
import
Point
Using the __init__.py
Using the __init__.py
• If we wish to import code directly from a package as opposed
to a module, we can use the _ _init_ _.py.
• So lets say we want to get the Point() class from the
module Point-docstrings.py.
• From the main directory we’d have to say:
import Drawing.Point-docstrings.Point()
Using the __init__.py
• If add the following code to the _ _init_ _.py in the
Drawing package:
from .Point-docstrings import Point()
• From the main directory now we can say:
import Drawing.Point()
• Instead of:
import Drawing.Point-docstrings.Point()
Using the __init__.py
• And if we want to import this class into any new module, all we
have to say is:
from Drawing import Point()
Using the __init__.py
• And if we want to import this class into any new module, all we
have to say is:
from Drawing import Point()
• It’s almost as if the _ _init_ _.py file converts the
Drawing package into a module!
Organizing Module Contents
Organizing Module Contents
• Inside a module we can specify variables, classes or methods.
• We can use modules to store global states without any
namespace conflicts.
• As well as classes, we can share global objects across a whole
system.
Organizing Module Contents
• If we think about an e-Commerce system again, which
connects to a database. There should be one Database class,
and one instance of a database object.
• Let’s look at the case where there are several local copies of
the database object.
Organizing Module Contents
• The Database module could look like:
class Database:
# The database implementation
pass
# End Database.
database1 = Database()
database.py
Organizing Module Contents
• And then any module could call the database as follow:
from ecommerce.database import database1
Organizing Module Contents
• There is potentially a problem with the previous
implementation, as soon of database.py is imported, the
database object is instantiated, if this does connect to a
database, it will cause a slight delay while the connection is
being made.
• If multiple connections are being made (multiple imports), this
will slow down the process.
Organizing Module Contents
• We could re-write as follows:
class Database:
# The database implementation
pass
# End Database.
database1 = None
def initialize_database():
global database1
database1 = Database()
# End initialize_database.
database.py
Organizing Module Contents
• Now that the variable database1 is global, all other modules
can access it.
• This prevents the system from instantiating a new database
object every time database.py is called.
Organizing Module Contents
• If we want to differentiate between when a module is being
called from another module, or is being called directly from the
command prompt (script), we can use the _ _main_ _
variable.
• We can do the following:
Organizing Module Contents
class UsefulClass:
“““This class might be useful to other modules”””
pass
# End UserfulClass.
def main():
global database1
database1 = Database()
# End main.
If _ _name_ _ == “_ _main_ _”:
main()
# Endif;
useful.py
Organizing Module Contents
• Up until now we have assumed that classes contain methods
and attributes, but in Python, we can have a class inside a
method.
• As follows:
Organizing Module Contents
def format_string(string, formatter=None):
'''Format a string using the formatter object, which is
expected to have a format() method that accepts a string.'''
class DefaultFormatter:
'''Format a string in title case.''‘
def format(self, string):
return str(string).title()
# End format.
# End Class.
Continued 
Organizing Module Contents
if not formatter:
formatter = DefaultFormatter()
# Endif;
return formatter.format(string)
# End format_string
hello_string = "hello world, how are you today?"
print(" input: " + hello_string)
print("output: " + format_string(hello_string))
 Continued
Organizing Module Contents
if not formatter:
formatter = DefaultFormatter()
# Endif;
return formatter.format(string)
# End format_string
hello_string = "hello world, how are you today?"
print(" input: " + hello_string)
print("output: " + format_string(hello_string))
input: hello world, how are you today?
output: Hello World, How Are You Today?
 Continued
Organizing Module Contents
• The format_string method accepts a string and optional
formatter object, which by default is set to None, so if the
method is called with no formatter, it will be treated as None.
• If no formatter is supplied, it creates a formatter of its own as a
local class and instantiates it. Since it is created inside the
scope of the function, this class cannot be accessed from
anywhere outside of that function.
etc.

More Related Content

What's hot (20)

Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Operators in python
Operators in pythonOperators in python
Operators 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
 
Python set
Python setPython set
Python set
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
List in Python
List in PythonList in Python
List in Python
 
Python basic
Python basicPython basic
Python basic
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Python libraries
Python librariesPython libraries
Python libraries
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
Python ppt
Python pptPython ppt
Python ppt
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 

Viewers also liked

Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party LibrariesDamian T. Gordon
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator PatternDamian T. Gordon
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programmingDamian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple InheritanceDamian T. Gordon
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in PythonDamian T. Gordon
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingDamian T. Gordon
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) ModelDamian T. Gordon
 

Viewers also liked (13)

Python: Design Patterns
Python: Design PatternsPython: Design Patterns
Python: Design Patterns
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator Pattern
 
Object-Orientated Design
Object-Orientated DesignObject-Orientated Design
Object-Orientated Design
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
 
Python: Access Control
Python: Access ControlPython: Access Control
Python: Access Control
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
Python: Manager Objects
Python: Manager ObjectsPython: Manager Objects
Python: Manager Objects
 
Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented Programming
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) Model
 

Similar to Python: Modules and Packages

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
 
Using Python Libraries.pdf
Using Python Libraries.pdfUsing Python Libraries.pdf
Using Python Libraries.pdfSoumyadityaDey
 
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
 
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
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
Interesting Presentation on Python Modules and packages
Interesting Presentation on Python Modules and packagesInteresting Presentation on Python Modules and packages
Interesting Presentation on Python Modules and packagesarunavamukherjee9999
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxRohitKumar639388
 
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptxkrushnaraj1
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1stConnex
 
Modules 101
Modules 101Modules 101
Modules 101gjcross
 
CLTL python course: Object Oriented Programming (2/3)
CLTL python course: Object Oriented Programming (2/3)CLTL python course: Object Oriented Programming (2/3)
CLTL python course: Object Oriented Programming (2/3)Rubén Izquierdo Beviá
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective cSunny Shaikh
 

Similar to Python: Modules and Packages (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
 
Using Python Libraries.pdf
Using Python Libraries.pdfUsing Python Libraries.pdf
Using Python Libraries.pdf
 
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
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
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
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Python for Beginners
Python  for BeginnersPython  for Beginners
Python for Beginners
 
Interesting Presentation on Python Modules and packages
Interesting Presentation on Python Modules and packagesInteresting Presentation on Python Modules and packages
Interesting Presentation on Python Modules and packages
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptx
 
packages.pptx
packages.pptxpackages.pptx
packages.pptx
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
Python training
Python trainingPython training
Python training
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
 
Modules 101
Modules 101Modules 101
Modules 101
 
CLTL python course: Object Oriented Programming (2/3)
CLTL python course: Object Oriented Programming (2/3)CLTL python course: Object Oriented Programming (2/3)
CLTL python course: Object Oriented Programming (2/3)
 
Group111
Group111Group111
Group111
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 

More from Damian T. Gordon

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Damian T. Gordon
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to MicroservicesDamian T. Gordon
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud ComputingDamian T. Gordon
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSDamian T. Gordon
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOTDamian T. Gordon
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricDamian T. Gordon
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDamian T. Gordon
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSUREDamian T. Gordon
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDamian T. Gordon
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDamian T. Gordon
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDamian T. Gordon
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsDamian T. Gordon
 

More from Damian T. Gordon (20)

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
REST and RESTful Services
REST and RESTful ServicesREST and RESTful Services
REST and RESTful Services
 
Serverless Computing
Serverless ComputingServerless Computing
Serverless Computing
 
Cloud Identity Management
Cloud Identity ManagementCloud Identity Management
Cloud Identity Management
 
Containers and Docker
Containers and DockerContainers and Docker
Containers and Docker
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud Computing
 
Introduction to ChatGPT
Introduction to ChatGPTIntroduction to ChatGPT
Introduction to ChatGPT
 
How to Argue Logically
How to Argue LogicallyHow to Argue Logically
How to Argue Logically
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONS
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOT
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson Rubric
 
Evaluating Teaching: LORI
Evaluating Teaching: LORIEvaluating Teaching: LORI
Evaluating Teaching: LORI
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause Procedure
 
Designing Teaching: ADDIE
Designing Teaching: ADDIEDesigning Teaching: ADDIE
Designing Teaching: ADDIE
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSURE
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning Types
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of Instruction
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration Theory
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some Considerations
 

Recently uploaded

4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 

Recently uploaded (20)

LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 

Python: Modules and Packages

  • 2. Modules and Packages • As we create more and more classes we need a way to organise them in such a way to make then available and easy to find. • Modules in Python are simply files, if you have two files in the same folder we can load a class from one module for use in the other module.
  • 3. Modules and Packages • As we create more and more classes we need a way to organise them in such a way to make then available and easy to find. • Modules in Python are simply files, if you have two files in the same folder we can load a class from one module for use in the other module.
  • 4. Modules and Packages • So, for example, if we are building an e-Commerce system, and we create a single file (module) that contains all the classes and methods related to accessing the database, then as long as all the other necessary modules (product, customer, inventory classes) are in the same folder, those modules can use the database module to access the database.
  • 5. Modules and Packages • So if we put our Point class in a file (module) called: – Pointdocstrings.py • We can create another file (module) to include that class, by doing the following: import Pointdocstrings p1 = Pointdocstrings.Point()
  • 6. Modules and Packages # PROGRAM Calling-Point-Docstrings: import Pointdocstrings p1 = Pointdocstrings.Point() p2 = Pointdocstrings.Point() p1.move(2,2) p2.move(6,5) print("CALLING: P1-x, P1-y is: ", p1.x, p1.y) print("CALLING: P2-x, P2-y is: ", p2.x, p2.y) print("CALLING: Distance from P1 to P2 is:", p1.calc_distance(p2)) # END.
  • 7. Modules and Packages • When we bring Pointdocstrings into the calling program, we say that Pointdocstrings is now part of the calling program’s namespace (which is the list of methods and classes available to the current program).
  • 8. Modules and Packages • If we just want to being one specific class in from a file (module) we simple say: from Pointdocstrings import Point And we can declare instances as follows: p1 = Point()
  • 9. Modules and Packages # PROGRAM Calling-Point-Docstrings: from Pointdocstrings import Point p1 = Point() p2 = Point() p1.move(2,2) p2.move(6,5) print("CALLING: P1-x, P1-y is: ", p1.x, p1.y) print("CALLING: P2-x, P2-y is: ", p2.x, p2.y) print("CALLING: Distance from P1 to P2 is:", p1.calc_distance(p2)) # END.
  • 10. Modules and Packages • If we already have a class called Point in the existing namespace, then we can use the as clause: from Pointdocstrings import Point as Pt And we can declare instances as follows: p1 = Pt()
  • 11. Modules and Packages # PROGRAM Calling-Point-Docstrings: from Pointdocstrings import Point as Pt p1 = Pt() p2 = Pt() p1.move(2,2) p2.move(6,5) print("CALLING: P1-x, P1-y is: ", p1.x, p1.y) print("CALLING: P2-x, P2-y is: ", p2.x, p2.y) print("CALLING: Distance from P1 to P2 is:", p1.calc_distance(p2)) # END.
  • 12. Modules and Packages • If we want to import more than one class we do: from Pointdocstrings import Point, Line But we should avoid doing this: from Pointdocstrings import *
  • 14. Modules and Packages • As projects get larger and larger it becomes more and more difficult to organise all of the modules (Python files) in a single folder. • To help with this issue, Python allows you to organise your modules into sub-folders (called Packages). The name of the package is the name of the folder.
  • 15. Modules and Packages • To achieve this we place a file called _ _init_ _.py in each sub-folder we wish to be included in the project. parent_directory/ main.py Drawing/ _ _init_ _.py point-call.py point-docstrings.py Maths/ _ _init_ _.py Theorem.py
  • 16. Modules and Packages • To achieve this we place a file called _ _init_ _.py in each sub-folder we wish to be included in the project. parent_directory/ main.py Drawing/ _ _init_ _.py point-call.py point-docstrings.py Maths/ _ _init_ _.py Theorem.py _ _init_ _.py
  • 17.
  • 18. Modules and Packages • For the moment we are going to assume that the special files, the _ _init_ _.py is empty. • We can import packages in two ways, using Absolute Imports and Relative Imports.
  • 19. Modules and Packages: Absolute Imports • An absolute import is an IMPORT where you fully specify the location of the classes being imported.
  • 20. Modules and Packages: Absolute Imports • We can do this in a number of ways: import Drawing.point-call P1 = point-call.Point() from Drawing.point-call import Point P1 = Point() from Drawing import point-call P1 = point-call.Point()
  • 21. Modules and Packages: Absolute Imports • We can do this in a number of ways: import Drawing.point-call P1 = point-call.Point() from Drawing.point-call import Point P1 = Point() from Drawing import point-call P1 = point-call.Point() PACKAGE MODULE PACKAGE MODULE CLASS PACKAGE MODULE
  • 22. Modules and Packages: Relative Imports • Relative Imports specific the location of the classes to be imported relative to the current package.
  • 23. Modules and Packages: Relative Imports • Relative Imports specific the location of the classes to be imported relative to the current package. The current directory (package) . The previous directory (package) ..
  • 25. Modules and Packages: Relative Imports If Point-call.py wants to call Point-docstrings.py, you can say: from .Point-docstrings.py import Point
  • 26. Modules and Packages: Relative Imports If Theorem.py wants to call Point-docstrings.py, you can say: from ..Point-docstrings.py import Point
  • 28. Using the __init__.py • If we wish to import code directly from a package as opposed to a module, we can use the _ _init_ _.py. • So lets say we want to get the Point() class from the module Point-docstrings.py. • From the main directory we’d have to say: import Drawing.Point-docstrings.Point()
  • 29. Using the __init__.py • If add the following code to the _ _init_ _.py in the Drawing package: from .Point-docstrings import Point() • From the main directory now we can say: import Drawing.Point() • Instead of: import Drawing.Point-docstrings.Point()
  • 30. Using the __init__.py • And if we want to import this class into any new module, all we have to say is: from Drawing import Point()
  • 31. Using the __init__.py • And if we want to import this class into any new module, all we have to say is: from Drawing import Point() • It’s almost as if the _ _init_ _.py file converts the Drawing package into a module!
  • 33. Organizing Module Contents • Inside a module we can specify variables, classes or methods. • We can use modules to store global states without any namespace conflicts. • As well as classes, we can share global objects across a whole system.
  • 34. Organizing Module Contents • If we think about an e-Commerce system again, which connects to a database. There should be one Database class, and one instance of a database object. • Let’s look at the case where there are several local copies of the database object.
  • 35. Organizing Module Contents • The Database module could look like: class Database: # The database implementation pass # End Database. database1 = Database() database.py
  • 36. Organizing Module Contents • And then any module could call the database as follow: from ecommerce.database import database1
  • 37. Organizing Module Contents • There is potentially a problem with the previous implementation, as soon of database.py is imported, the database object is instantiated, if this does connect to a database, it will cause a slight delay while the connection is being made. • If multiple connections are being made (multiple imports), this will slow down the process.
  • 38. Organizing Module Contents • We could re-write as follows: class Database: # The database implementation pass # End Database. database1 = None def initialize_database(): global database1 database1 = Database() # End initialize_database. database.py
  • 39. Organizing Module Contents • Now that the variable database1 is global, all other modules can access it. • This prevents the system from instantiating a new database object every time database.py is called.
  • 40. Organizing Module Contents • If we want to differentiate between when a module is being called from another module, or is being called directly from the command prompt (script), we can use the _ _main_ _ variable. • We can do the following:
  • 41. Organizing Module Contents class UsefulClass: “““This class might be useful to other modules””” pass # End UserfulClass. def main(): global database1 database1 = Database() # End main. If _ _name_ _ == “_ _main_ _”: main() # Endif; useful.py
  • 42. Organizing Module Contents • Up until now we have assumed that classes contain methods and attributes, but in Python, we can have a class inside a method. • As follows:
  • 43. Organizing Module Contents def format_string(string, formatter=None): '''Format a string using the formatter object, which is expected to have a format() method that accepts a string.''' class DefaultFormatter: '''Format a string in title case.''‘ def format(self, string): return str(string).title() # End format. # End Class. Continued 
  • 44. Organizing Module Contents if not formatter: formatter = DefaultFormatter() # Endif; return formatter.format(string) # End format_string hello_string = "hello world, how are you today?" print(" input: " + hello_string) print("output: " + format_string(hello_string))  Continued
  • 45. Organizing Module Contents if not formatter: formatter = DefaultFormatter() # Endif; return formatter.format(string) # End format_string hello_string = "hello world, how are you today?" print(" input: " + hello_string) print("output: " + format_string(hello_string)) input: hello world, how are you today? output: Hello World, How Are You Today?  Continued
  • 46. Organizing Module Contents • The format_string method accepts a string and optional formatter object, which by default is set to None, so if the method is called with no formatter, it will be treated as None. • If no formatter is supplied, it creates a formatter of its own as a local class and instantiates it. Since it is created inside the scope of the function, this class cannot be accessed from anywhere outside of that function.
  • 47. etc.