6.Modules¶
If you quit from the Python interpreter and enter it again, the definitions youhave made (functions and variables) are lost. Therefore, if you want to write asomewhat longer program, you are better off using a text editor to prepare theinput for the interpreter and running it with that file as input instead. Thisis known as creating ascript. As your program gets longer, you may want tosplit it into several files for easier maintenance. You may also want to use ahandy function that you’ve written in several programs without copying itsdefinition into each program.
To support this, Python has a way to put definitions in a file and use them in ascript or in an interactive instance of the interpreter. Such a file is called amodule; definitions from a module can beimported into other modules or intothemain module (the collection of variables that you have access to in ascript executed at the top level and in calculator mode).
A module is a file containing Python definitions and statements. The file nameis the module name with the suffix.py
appended. Within a module, themodule’s name (as a string) is available as the value of the global variable__name__
. For instance, use your favorite text editor to create a filecalledfibo.py
in the current directory with the following contents:
# Fibonacci numbers moduledeffib(n):# write Fibonacci series up to na,b=0,1whileb<n:printb,a,b=b,a+bdeffib2(n):# return Fibonacci series up to nresult=[]a,b=0,1whileb<n:result.append(b)a,b=b,a+breturnresult
Now enter the Python interpreter and import this module with the followingcommand:
>>>importfibo
This does not enter the names of the functions defined infibo
directly inthe current symbol table; it only enters the module namefibo
there. Usingthe module name you can access the functions:
>>>fibo.fib(1000)1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987>>>fibo.fib2(100)[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]>>>fibo.__name__'fibo'
If you intend to use a function often you can assign it to a local name:
>>>fib=fibo.fib>>>fib(500)1 1 2 3 5 8 13 21 34 55 89 144 233 377
6.1.More on Modules¶
A module can contain executable statements as well as function definitions.These statements are intended to initialize the module. They are executed onlythefirst time the module name is encountered in an import statement.1(They are also run if the file is executed as a script.)
Each module has its own private symbol table, which is used as the global symboltable by all functions defined in the module. Thus, the author of a module canuse global variables in the module without worrying about accidental clasheswith a user’s global variables. On the other hand, if you know what you aredoing you can touch a module’s global variables with the same notation used torefer to its functions,modname.itemname
.
Modules can import other modules. It is customary but not required to place allimport
statements at the beginning of a module (or script, for thatmatter). The imported module names are placed in the importing module’s globalsymbol table.
There is a variant of theimport
statement that imports names from amodule directly into the importing module’s symbol table. For example:
>>>fromfiboimportfib,fib2>>>fib(500)1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken in thelocal symbol table (so in the example,fibo
is not defined).
There is even a variant to import all names that a module defines:
>>>fromfiboimport*>>>fib(500)1 1 2 3 5 8 13 21 34 55 89 144 233 377
This imports all names except those beginning with an underscore (_
).
Note that in general the practice of importing*
from a module or package isfrowned upon, since it often causes poorly readable code. However, it is okay touse it to save typing in interactive sessions.
If the module name is followed byas
, then the namefollowingas
is bound directly to the imported module.
>>>importfiboasfib>>>fib.fib(500)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This is effectively importing the module in the same way thatimportfibo
will do, with the only difference of it being available asfib
.
It can also be used when utilisingfrom
with similar effects:
>>>fromfiboimportfibasfibonacci>>>fibonacci(500)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Note
For efficiency reasons, each module is only imported once per interpretersession. Therefore, if you change your modules, you must restart theinterpreter – or, if it’s just one module you want to test interactively,usereload()
, e.g.reload(modulename)
.
6.1.1.Executing modules as scripts¶
When you run a Python module with
pythonfibo.py<arguments>
the code in the module will be executed, just as if you imported it, but withthe__name__
set to"__main__"
. That means that by adding this code atthe end of your module:
if__name__=="__main__":importsysfib(int(sys.argv[1]))
you can make the file usable as a script as well as an importable module,because the code that parses the command line only runs if the module isexecuted as the “main” file:
$ python fibo.py501 1 2 3 5 8 13 21 34
If the module is imported, the code is not run:
>>>importfibo>>>
This is often used either to provide a convenient user interface to a module, orfor testing purposes (running the module as a script executes a test suite).
6.1.2.The Module Search Path¶
When a module namedspam
is imported, the interpreter first searches fora built-in module with that name. If not found, it then searches for a filenamedspam.py
in a list of directories given by the variablesys.path
.sys.path
is initialized from these locations:
the directory containing the input script (or the current directory).
PYTHONPATH
(a list of directory names, with the same syntax as theshell variablePATH
).the installation-dependent default.
After initialization, Python programs can modifysys.path
. Thedirectory containing the script being run is placed at the beginning of thesearch path, ahead of the standard library path. This means that scripts in thatdirectory will be loaded instead of modules of the same name in the librarydirectory. This is an error unless the replacement is intended. See sectionStandard Modules for more information.
6.1.3.“Compiled” Python files¶
As an important speed-up of the start-up time for short programs that use a lotof standard modules, if a file calledspam.pyc
exists in the directorywherespam.py
is found, this is assumed to contain analready-“byte-compiled” version of the modulespam
. The modification timeof the version ofspam.py
used to createspam.pyc
is recorded inspam.pyc
, and the.pyc
file is ignored if these don’t match.
Normally, you don’t need to do anything to create thespam.pyc
file.Wheneverspam.py
is successfully compiled, an attempt is made to writethe compiled version tospam.pyc
. It is not an error if this attemptfails; if for any reason the file is not written completely, the resultingspam.pyc
file will be recognized as invalid and thus ignored later. Thecontents of thespam.pyc
file are platform independent, so a Pythonmodule directory can be shared by machines of different architectures.
Some tips for experts:
When the Python interpreter is invoked with the
-O
flag, optimizedcode is generated and stored in.pyo
files. The optimizer currentlydoesn’t help much; it only removesassert
statements. When-O
is used,allbytecode is optimized;.pyc
files areignored and.py
files are compiled to optimized bytecode.Passing two
-O
flags to the Python interpreter (-OO
) willcause the bytecode compiler to perform optimizations that could in some rarecases result in malfunctioning programs. Currently only__doc__
strings areremoved from the bytecode, resulting in more compact.pyo
files. Sincesome programs may rely on having these available, you should only use thisoption if you know what you’re doing.A program doesn’t run any faster when it is read from a
.pyc
or.pyo
file than when it is read from a.py
file; the only thingthat’s faster about.pyc
or.pyo
files is the speed with whichthey are loaded.When a script is run by giving its name on the command line, the bytecode forthe script is never written to a
.pyc
or.pyo
file. Thus, thestartup time of a script may be reduced by moving most of its code to a moduleand having a small bootstrap script that imports that module. It is alsopossible to name a.pyc
or.pyo
file directly on the commandline.It is possible to have a file called
spam.pyc
(orspam.pyo
when-O
is used) without a filespam.py
for the same module.This can be used to distribute a library of Python code in a form that ismoderately hard to reverse engineer.The module
compileall
can create.pyc
files (or.pyo
files when-O
is used) for all modules in a directory.
6.2.Standard Modules¶
Python comes with a library of standard modules, described in a separatedocument, the Python Library Reference (“Library Reference” hereafter). Somemodules are built into the interpreter; these provide access to operations thatare not part of the core of the language but are nevertheless built in, eitherfor efficiency or to provide access to operating system primitives such assystem calls. The set of such modules is a configuration option which alsodepends on the underlying platform. For example, thewinreg
module is onlyprovided on Windows systems. One particular module deserves some attention:sys
, which is built into every Python interpreter. The variablessys.ps1
andsys.ps2
define the strings used as primary and secondaryprompts:
>>>importsys>>>sys.ps1'>>> '>>>sys.ps2'... '>>>sys.ps1='C> 'C> print 'Yuck!'Yuck!C>
These two variables are only defined if the interpreter is in interactive mode.
The variablesys.path
is a list of strings that determines the interpreter’ssearch path for modules. It is initialized to a default path taken from theenvironment variablePYTHONPATH
, or from a built-in default ifPYTHONPATH
is not set. You can modify it using standard listoperations:
>>>importsys>>>sys.path.append('/ufs/guido/lib/python')
6.3.Thedir()
Function¶
The built-in functiondir()
is used to find out which names a moduledefines. It returns a sorted list of strings:
>>>importfibo,sys>>>dir(fibo)['__name__', 'fib', 'fib2']>>>dir(sys)['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettotalrefcount', 'gettrace', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
Without arguments,dir()
lists the names you have defined currently:
>>>a=[1,2,3,4,5]>>>importfibo>>>fib=fibo.fib>>>dir()['__builtins__', '__name__', '__package__', 'a', 'fib', 'fibo', 'sys']
Note that it lists all types of names: variables, modules, functions, etc.
dir()
does not list the names of built-in functions and variables. If youwant a list of those, they are defined in the standard module__builtin__
:
>>>import__builtin__>>>dir(__builtin__)['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
6.4.Packages¶
Packages are a way of structuring Python’s module namespace by using “dottedmodule names”. For example, the module nameA.B
designates a submodulenamedB
in a package namedA
. Just like the use of modules saves theauthors of different modules from having to worry about each other’s globalvariable names, the use of dotted module names saves the authors of multi-modulepackages like NumPy or Pillow from having to worry abouteach other’s module names.
Suppose you want to design a collection of modules (a “package”) for the uniformhandling of sound files and sound data. There are many different sound fileformats (usually recognized by their extension, for example:.wav
,.aiff
,.au
), so you may need to create and maintain a growingcollection of modules for the conversion between the various file formats.There are also many different operations you might want to perform on sound data(such as mixing, adding echo, applying an equalizer function, creating anartificial stereo effect), so in addition you will be writing a never-endingstream of modules to perform these operations. Here’s a possible structure foryour package (expressed in terms of a hierarchical filesystem):
sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Subpackage for sound effects __init__.py echo.py surround.py reverse.py ... filters/ Subpackage for filters __init__.py equalizer.py vocoder.py karaoke.py ...
When importing the package, Python searches through the directories onsys.path
looking for the package subdirectory.
The__init__.py
files are required to make Python treat the directoriesas containing packages; this is done to prevent directories with a common name,such asstring
, from unintentionally hiding valid modules that occur lateron the module search path. In the simplest case,__init__.py
can just bean empty file, but it can also execute initialization code for the package orset the__all__
variable, described later.
Users of the package can import individual modules from the package, forexample:
importsound.effects.echo
This loads the submodulesound.effects.echo
. It must be referenced withits full name.
sound.effects.echo.echofilter(input,output,delay=0.7,atten=4)
An alternative way of importing the submodule is:
fromsound.effectsimportecho
This also loads the submoduleecho
, and makes it available without itspackage prefix, so it can be used as follows:
echo.echofilter(input,output,delay=0.7,atten=4)
Yet another variation is to import the desired function or variable directly:
fromsound.effects.echoimportechofilter
Again, this loads the submoduleecho
, but this makes its functionechofilter()
directly available:
echofilter(input,output,delay=0.7,atten=4)
Note that when usingfrompackageimportitem
, the item can be either asubmodule (or subpackage) of the package, or some other name defined in thepackage, like a function, class or variable. Theimport
statement firsttests whether the item is defined in the package; if not, it assumes it is amodule and attempts to load it. If it fails to find it, anImportError
exception is raised.
Contrarily, when using syntax likeimportitem.subitem.subsubitem
, each itemexcept for the last must be a package; the last item can be a module or apackage but can’t be a class or function or variable defined in the previousitem.
6.4.1.Importing * From a Package¶
Now what happens when the user writesfromsound.effectsimport*
? Ideally,one would hope that this somehow goes out to the filesystem, finds whichsubmodules are present in the package, and imports them all. This could take along time and importing sub-modules might have unwanted side-effects that shouldonly happen when the sub-module is explicitly imported.
The only solution is for the package author to provide an explicit index of thepackage. Theimport
statement uses the following convention: if a package’s__init__.py
code defines a list named__all__
, it is taken to be thelist of module names that should be imported whenfrompackageimport*
isencountered. It is up to the package author to keep this list up-to-date when anew version of the package is released. Package authors may also decide not tosupport it, if they don’t see a use for importing * from their package. Forexample, the filesound/effects/__init__.py
could contain the followingcode:
__all__=["echo","surround","reverse"]
This would mean thatfromsound.effectsimport*
would import the threenamed submodules of thesound
package.
If__all__
is not defined, the statementfromsound.effectsimport*
doesnot import all submodules from the packagesound.effects
into thecurrent namespace; it only ensures that the packagesound.effects
hasbeen imported (possibly running any initialization code in__init__.py
)and then imports whatever names are defined in the package. This includes anynames defined (and submodules explicitly loaded) by__init__.py
. Italso includes any submodules of the package that were explicitly loaded bypreviousimport
statements. Consider this code:
importsound.effects.echoimportsound.effects.surroundfromsound.effectsimport*
In this example, theecho
andsurround
modules are imported in thecurrent namespace because they are defined in thesound.effects
packagewhen thefrom...import
statement is executed. (This also works when__all__
is defined.)
Although certain modules are designed to export only names that follow certainpatterns when you useimport*
, it is still considered bad practice inproduction code.
Remember, there is nothing wrong with usingfrompackageimportspecific_submodule
! In fact, this is the recommended notation unless theimporting module needs to use submodules with the same name from differentpackages.
6.4.2.Intra-package References¶
The submodules often need to refer to each other. For example, thesurround
module might use theecho
module. In fact, suchreferences are so common that theimport
statement first looks in thecontaining package before looking in the standard module search path. Thus, thesurround
module can simply useimportecho
orfromechoimportechofilter
. If the imported module is not found in the current package (thepackage of which the current module is a submodule), theimport
statement looks for a top-level module with the given name.
When packages are structured into subpackages (as with thesound
packagein the example), you can use absolute imports to refer to submodules of siblingspackages. For example, if the modulesound.filters.vocoder
needs to usetheecho
module in thesound.effects
package, it can usefromsound.effectsimportecho
.
Starting with Python 2.5, in addition to the implicit relative imports describedabove, you can write explicit relative imports with thefrommoduleimportname
form of import statement. These explicit relative imports use leadingdots to indicate the current and parent packages involved in the relativeimport. From thesurround
module for example, you might use:
from.importechofrom..importformatsfrom..filtersimportequalizer
Note that both explicit and implicit relative imports are based on the name ofthe current module. Since the name of the main module is always"__main__"
,modules intended for use as the main module of a Python application shouldalways use absolute imports.
6.4.3.Packages in Multiple Directories¶
Packages support one more special attribute,__path__
. This isinitialized to be a list containing the name of the directory holding thepackage’s__init__.py
before the code in that file is executed. Thisvariable can be modified; doing so affects future searches for modules andsubpackages contained in the package.
While this feature is not often needed, it can be used to extend the set ofmodules found in a package.
Footnotes
- 1
In fact function definitions are also ‘statements’ that are ‘executed’; theexecution of a module-level function definition enters the function name inthe module’s global symbol table.