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,1whilea<n:print(a,end=' ')a,b=b,a+bprint()deffib2(n):# return Fibonacci series up to nresult=[]a,b=0,1whilea<n:result.append(a)a,b=b,a+breturnresult
Now enter the Python interpreter and import this module with the followingcommand:
>>>importfibo
This does not add the names of the functions defined infibo
directly tothe currentnamespace (seePython Scopes and Namespaces for more details);it only adds the module namefibo
there. Usingthe module name you can access the functions:
>>>fibo.fib(1000)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987>>>fibo.fib2(100)[0, 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)0 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 namespace, which is used as the global namespaceby 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, if placed at the top level of a module(outside any functions or classes), are added to the module’s global namespace.
There is a variant of theimport
statement that imports names from amodule directly into the importing module’s namespace. For example:
>>>fromfiboimportfib,fib2>>>fib(500)0 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 namespace (so in the example,fibo
is not defined).
There is even a variant to import all names that a module defines:
>>>fromfiboimport*>>>fib(500)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This imports all names except those beginning with an underscore (_
).In most cases Python programmers do not use this facility since it introducesan unknown set of names into the interpreter, possibly hiding some thingsyou have already defined.
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,useimportlib.reload()
, e.g.importimportlib;importlib.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:
$pythonfibo.py500 1 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. These module names are listed insys.builtin_module_names
. 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 when nofile is specified).
PYTHONPATH
(a list of directory names, with the same syntax as theshell variablePATH
).The installation-dependent default (by convention including a
site-packages
directory, handled by thesite
module).
More details are atThe initialization of the sys.path module search path.
Note
On file systems which support symlinks, the directory containing the inputscript is calculated after the symlink is followed. In other words thedirectory containing the symlink isnot added to the module search path.
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¶
To speed up loading modules, Python caches the compiled version of each modulein the__pycache__
directory under the namemodule.version.pyc
,where the version encodes the format of the compiled file; it generally containsthe Python version number. For example, in CPython release 3.3 the compiledversion of spam.py would be cached as__pycache__/spam.cpython-33.pyc
. Thisnaming convention allows compiled modules from different releases and differentversions of Python to coexist.
Python checks the modification date of the source against the compiled versionto see if it’s out of date and needs to be recompiled. This is a completelyautomatic process. Also, the compiled modules are platform-independent, so thesame library can be shared among systems with different architectures.
Python does not check the cache in two circumstances. First, it alwaysrecompiles and does not store the result for the module that’s loaded directlyfrom the command line. Second, it does not check the cache if there is nosource module. To support a non-source (compiled only) distribution, thecompiled module must be in the source directory, and there must not be a sourcemodule.
Some tips for experts:
You can use the
-O
or-OO
switches on the Python commandto reduce the size of a compiled module. The-O
switch removes assertstatements, the-OO
switch removes both assert statements and __doc__strings. Since some programs may rely on having these available, you shouldonly use this option if you know what you’re doing. “Optimized” modules haveanopt-
tag and are usually smaller. Future releases maychange the effects of optimization.A program doesn’t run any faster when it is read from a
.pyc
file than when it is read from a.py
file; the only thing that’s fasterabout.pyc
files is the speed with which they are loaded.The module
compileall
can create .pyc files for all modules in adirectory.There is more detail on this process, including a flow chart of thedecisions, inPEP 3147.
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)['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework', '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook', 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix', 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'unraisablehook', '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__', '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 modulebuiltins
:
>>>importbuiltins>>>dir(builtins)['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', '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 directoriescontaining the file as packages (unless using anamespace package, arelatively advanced feature). This prevents 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.effects
package.
Be aware that submodules might become shadowed by locally defined names. Forexample, if you added areverse
function to thesound/effects/__init__.py
file, thefromsound.effectsimport*
would only import the two submodulesecho
andsurround
, butnot thereverse
submodule, because it is shadowed by the locally definedreverse
function:
__all__=["echo",# refers to the 'echo.py' file"surround",# refers to the 'surround.py' file"reverse",# !!! refers to the 'reverse' function now !!!]defreverse(msg:str):# <-- this name shadows the 'reverse.py' submodulereturnmsg[::-1]# in the case of a 'from sound.effects import *'
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¶
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
.
You can also write relative imports, with thefrommoduleimportname
formof import statement. These imports use leading dots to indicate the current andparent packages involved in the relative import. From thesurround
module for example, you might use:
from.importechofrom..importformatsfrom..filtersimportequalizer
Note that relative imports are based on the name of the current module. Sincethe name of the main module is always"__main__"
, modules intended for useas the main module of a Python application must always use absolute imports.
6.4.3.Packages in Multiple Directories¶
Packages support one more special attribute,__path__
. This isinitialized to be asequence of strings containing the name of thedirectory 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 adds the function name tothe module’s global namespace.