Lecture 09
Lecture 09
def add(x,y):
return x + y
def sub(x,y):
return x - y
• 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
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
main.py mymath.py
7 def sub(x,y):
The output return x – y
of main.py 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.
main.py
import mymath mymath.py
m = 1
# mymath.py
n = 13
pi = 3.14
mymath.add(m,n)
mymath.sub(m,n) def add(x,y):
print(mymath.pi) return x + y
14 def sub(x,y):
-12 return x – y
3.14
The output of main.py 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: mymath.py
# mymath.py
import mymath as m
pi = 3.14
m = 1
n = 13
def add(x,y):
m.add(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.
8
The from...import Statement Cont’d
Example
main.py mymath.py
from mymath import add
# mymath.py
m = 1
n = 13
pi = 3.14
def sub(x,y):
return x – y
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
10
The from...import * Statement
• Example
main.py mymath.py
from mymath import * # mymath.py
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
12
Module Names
13
Naming Conventions
• It is standard practice for package and module
names to be concise and lowercase
person.py Not ThePersonModule.py
• 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)
math.py os.py
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:
mymath.py
main.py
import mymath # mymath.py
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__' .
def add(x,y):
main.py return x + y
if __name__ != '__main__':
print('Run in the imported')
Run in mymath 17
How Imports Work?
18
How Imports Work?
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
Note: The exact contents of sys.path are installation-dependent. The above will
almost certainly look slightly different on your computer.
21
Modify sys.path
• One additional option that you can create a module
file in any directory and then modify sys.path at
run-time by adding the new directory.
import sys
sys.path.append(“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\mymath.py
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.
26
How Imports Work?
27
3- Run the module’s code
• The final step of an import operation executes the
byte code of the module.
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
imp.reload function.
• reloading looks like this:
import module # Initial import
...use module.attributes...
... # Now, go change the module file
...
from imp import reload # Get reload itself
reload(module) # Get updated
...use module.attributes...
29