Modules and Packages Damian Gordon.

Slides:



Advertisements
Similar presentations
Python Objects and Classes
Advertisements

15. Python - Modules A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand.
Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
This Week More Types boolean string Modules print statement Writing programs if statement Type boolean.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
VBA Modules, Functions, Variables, and Constants
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
An Introduction to Python – Part IV Dr. Nancy Warter-Perez.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
Python Modules An Introduction. Introduction A module is a file containing Python definitions and statements. The file name is the module name with the.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
PHP - Basic Language Constructs CSCI 297 Scripting Languages - Day Two.
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
Python Functions.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
ProgLan Python Session 4. Functions are a convenient way to divide your code into useful blocks, allowing us to: order our code, make it more readable,
Python Let’s get started!.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
Modules. Modules Modules are the highest level program organization unit, usually correspond to source files and serve as libraries of tools. Each file.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
ENGINEERING 1D04 Tutorial 4. What are we doing today? Focus Functions Scope of Variables Returning Values Objects Graphics library Aliasing Events Mouse.
Object-Orientated Design (Summary)
Development Environment
Python’s Modules Noah Black.
A Playful Introduction to Programming by Jason R. Briggs
3 Introduction to Classes and Objects.
Lecture 2 Python Basics.
Classes and objects You can define many objects of the same class:
Python Let’s get started!.
Review What is an object? What is a class?
Functions CIS 40 – Introduction to Programming in Python
Functions.
Writing modules and packages
Creating and Deleting Instances Access to Attributes and Methods
Python Classes By Craig Pennell.
CSC240 Computer Science III
CHAPTER FOUR Functions.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Functions BIS1523 – Lecture 17.
Topics Introduction to File Input and Output
Number and String Operations
Functions, Procedures, and Abstraction
Functions and Procedures
Building Web Applications
Python Lessons 13 & 14 Mr. Kalmes.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Basic Inheritance Damian Gordon.
Getting your metadata using PROC METADATA
Tonga Institute of Higher Education
Python programming exercise
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
G. Pullaiah College of Engineering and Technology
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Lab 4: Introduction to Scripting
Compiler vs linker The compiler translates one .c file into a .o file
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
Migrating to Object-Oriented Programs
CMPE212 – Reminders Assignment 2 due next Friday.
SQL – Application Persistence Design Patterns
Review We've seen that a module is a file that can contain classes as well as its own variables. We've seen that you need to import it to access the code,
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Functions John R. Woodward.
Presentation transcript:

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.

AMAZING 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. AMAZING

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/ 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/ 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 OR: OR:

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 PACKAGE MODULE PACKAGE MODULE CLASS OR: PACKAGE MODULE OR:

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 import Point

Modules and Packages: Relative Imports If Theorem.py wants to call Point-docstrings.py, you can say: from ..Point-docstrings import Point

Using the _ _init_ _.py

import Drawing.Point-docstrings.Point 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

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

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  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))

Organizing Module Contents  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?

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.