Module
• Each file in Python is considered a module.
Everything within the file is encapsulated within a
namespace (which is the name of the file)
• Why Modules?
• Reuse code
• Manage large projects
• Professional projects can be hundreds of thousands of
lines long
• Would be nearly impossible to maintain in one file
1
Creating a Module
• A module is a file containing Python definitions and
statements.
• The file name is the module name with the
suffix .py appended.
• Within a module, the module’s name (as a string) is
available as the value of the global variable
__name__.
• For Example: use your text editor to create a file
called [Link] in the current directory with the
following contents (in the next slide):
2
Creating a Module
Any Python source file is a module
# [Link]
pi = 3.14
def add(x,y):
return x + y
def sub(x,y):
return x - y
Several objects are defined in [Link] file:
• pi : Float
• add : Function
• sub : Function
3
How to use the Module?
• You can use any Python source file as a module by
executing an import statement in another Python
source file.
• import has the following syntax:
import modulename
• To use the module mymath, we just type:
import mymath
4
Module Execution
• When a module is imported, all of the statements in
the module execute one after another until the end of
the file is reached
• If there are scripting statements that carry out tasks in
the global scope (printing, creating files, etc.), you will
see them run on import
[Link] [Link]
import mymath # [Link]
x = 1 pi = 3.14
Y = 13
def add(x,y):
return x + y
7 def sub(x,y):
The output return x – y
of [Link] add(2,5) 5
Access to the imported objects
• Objects (variables, Functions, Classes,… etc.) in any
module can be accessed using the module’s name,
a dot (.) and the object name.
[Link]
import mymath [Link]
m = 1
# [Link]
n = 13
pi = 3.14
[Link](m,n)
[Link](m,n) def add(x,y):
print([Link]) return x + y
14 def sub(x,y):
-12 return x – y
3.14
The output of [Link] 6
Import by alias
• For longer module names, it's not convenient to use
the full module name each time you access some
element.
• For this reason, you can use the "import ... as ..."
pattern to create a shorter alias for the namespace.
• Example: [Link]
# [Link]
import mymath as m
pi = 3.14
m = 1
n = 13
def add(x,y):
[Link](m,n) return x + y
def sub(x,y):
return x – y 7
The from...import Statement
• Python's from statement lets you import specific
attributes from a module into the current
namespace.
• Allows parts of a module to be used without having
to type the module prefix
• The from...import has the following syntax −
from modulename import name1[name2 ..]
8
The from...import Statement Cont’d
Example
[Link] [Link]
from mymath import add
# [Link]
m = 1
n = 13
pi = 3.14
add(m,n) def add(x,y):
return x + y
def sub(x,y):
return x – y
• This statement does not import the entire module mymath
into the current namespace; it just introduces the item add.
• You cannot use the function sub in the main program
9
The from...import * Statement
• It is also possible to import all names from a
module into the current namespace by using the
following import statement
from modulename import *
• Takes all symbols from a module and places them
into local scope
10
The from...import * Statement
• Example
[Link] [Link]
from mymath import * # [Link]
m = 1 pi = 3.14
n = 13
def add(x,y):
add(m,n)
return x + y
sub(m,n)
print (pi)
def sub(x,y):
return x – y
This provides an easy way to import all the items from a
module into the current namespace; however, this
Usually considered bad style (try to avoid)
11
Commentary
• Variations on import do not change the way that
modules work
• import mymath as m
• from mymath import add, sub
• from mymath import *
• ...
• import always executes the entire file
• Modules are still isolated environments
• These variations are just manipulating names
12
Module Names
• File names have to follow the rules
• avoid non-ASCII characters
13
Naming Conventions
• It is standard practice for package and module
names to be concise and lowercase
[Link] Not [Link]
• Use a leading underscore for modules that are
meant to be private or internal
_person.py
• Don't use names that match common standard
library modules (confusing)
[Link] [Link]
14
The dir() Function
• The built-in function dir() returns a list of defined
names in a namespace. Without arguments, it
produces an alphabetically sorted list of names in
the current local symbol table:
[Link]
[Link]
import mymath # [Link]
print(dir(mymath)) pi = 3.14
def add(x,y):
['__builtins__', '__cached__', '__doc__', return x + y
'__file__', '__loader__', '__name__',
'__package__', '__spec__', 'add', 'pi', 'sub'] def sub(x,y):
return x – y
15
__main__ check
• Python module can test if the module is being used
as the main program by checking if global variable
__name__ has the value '__main__' .
• If a file might run as a main program, do this
...
if __name__ == '__main__':
# Running as the main program
...
• Such code would not run on library import
__main__ check
Cont’d
[Link]
• Example pi = 3.14
def add(x,y):
[Link] return x + y
import mymath def sub(x,y):
pass return x - y
Run in the imported if __name__ == '__main__':
print('Run in mymath')
if __name__ != '__main__':
print('Run in the imported')
Run in mymath 17
How Imports Work?
1. Find the module’s file.
2. Compile it to byte code (if needed).
3. Run the module’s code
18
How Imports Work?
1. Find the module’s file.
2. Compile it to byte code (if needed).
3. Run the module’s code
19
1- Find the module’s file
• When you import a module, the Python interpreter
searches for the module in the following sequences
1) The current directory.
2) If the module isn't found, Python then searches each
directory in the shell variable PYTHONPATH.
3) Standard library directories
• The module search path is stored in the system module
sys as the [Link] variable. The [Link] variable
contains the current directory, PYTHONPATH, and the
installation-dependent default.
20
The [Link] List
• The resulting search path is accessible in the
Python variable [Link], which is obtained from a
module named sys:
import sys
print([Link])
['C:\\Users\\User\\PycharmProjects\\test2\\venv\\Scripts\\[Link]',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\
Users\\User\\PycharmProjects\\test2\\venv', 'C:\\Users\\User\\
PycharmProjects\\test2\\venv\\lib\\site-packages',
Note: The exact contents of [Link] are installation-dependent. The above will
almost certainly look slightly different on your computer.
21
Modify [Link]
• One additional option that you can create a module
file in any directory and then modify [Link] at
run-time by adding the new directory.
• The [Link] will contain the new directory.
• For example, if you create [Link] module in
directory C:\Users\myproject and then use the
following statements:
import sys
[Link](“C:\Users\myproject")
import mymath
22
Determine the Location
• Once a module has been imported, you can determine the
location where it was found with the module’s __file__
attribute:
import mymath
print(mymath.__file__)
C:\Users\User\.PyCharmCE2018.2\config\scratches\[Link]
• Or by using module’s name:
print(mymath)
<module 'mymath' from 'C:\\Users\\User\\.PyCharmCE2018.2\\config\\
scratches\\[Link]'>
23
How Imports Work?
1. Find the module’s file.
2. Compile it to byte code (if needed).
3. Run the module’s code
24
2- Compile it to byte code (if
needed)
• After finding a source code file that matches an import
statement, Python next chooses an action as follows:
Compile :
• if it has not compiled before. Then python will store
the byte code of your programs in files that end with a
.pyc extension (“.pyc” means compiled “.py” source).
• If the byte code file is older than the source file (i.e., if
you’ve changed the source), Then will be compiled
again.
• byte code files are stored in a __pycache__
subdirectory
25
2- Compile it to byte code (if
needed)
Don’t compile:
• Python finds a .pyc byte code file that is not
older than the corresponding .py source file and
was created by the same Python version, it skips
the source-to-byte-code compile step.
• If Python finds only a byte code file on the
search path and no source, it simply loads the
byte code directly.
26
How Imports Work?
1. Find the module’s file.
2. Compile it to byte code (if needed).
3. Run the module’s code
27
3- Run the module’s code
• The final step of an import operation executes the
byte code of the module.
• if any top-level code in a module file does real
work, you will see its results at import time.
• For example, top-level print statements in a module
show output when the file is imported. Function
def statements simply define objects for later use.
28
Reloading Modules
• Python loads a module only the first time you
import the module during a program run.
• However, If a module has changed, you can reload
the new definition of the module using the
[Link] function.
• reloading looks like this:
import module # Initial import
...use [Link]...
... # Now, go change the module file
...
from imp import reload # Get reload itself
reload(module) # Get updated
...use [Link]...
29