Modules and Packages
Modules and Packages
1
Module
s
• Any Python source
# spam.py
file is a module
def
grok(x):
...
def
blah(x):
...
• You use
import to
execute
and
access it
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com 2
import spam
Namespaces
• Each module is its own isolated world
# spam.py #
eggs.py
x = 42
def blah(): These definitions of x x foo():
= 37
print(x
def are different
)
print(x)
spam.py
x = 42
def
blah():
prin
t(x)
• Functi
ons
record
their
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com 4
definit
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
• The contents of the module namespace are all
of the global names that are still defined at the
end of the execution process
• If there are scripting statements that carry out
tasks in the global scope (printing, creating
files, etc.), you will see them run on import
def rectangular(r,
theta): x = r *
cos(theta)
y = r * sin(theta)
return x, y
def rectangular(r,
theta): x = r *
cos(theta)
y = r * sin(theta)
return x, y
• Sometimes useful
• Usually considered bad style (try to avoid)
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com 7
Commentary
• Variations on import do not change the way
that modules work
import math as m
from math import cos,
sin from math import *
...
• import always
executes the entire
file
• Modules are still
isolated
environments
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com 8
Module Names
• File names have to follow the rules
Yes
# good.py # 2bad.py
No
... ...
...
if name == ' main ':
# Running as the main program
...
executes
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com 14