Modules
Published:
This lesson covers An Informal Introduction to Python 3.10.5, https://docs.python.org/3/tutorial/introduction.html
Introduction
- 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_$
# fibo.py
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
import fibo
fibo.fib(30) # 0 1 1 2 3 5 8 13 21
print(fibo.fib2(30)) # [0, 1, 1, 2, 3, 5, 8, 13, 21]
print(fibo.__name__) # 'fibo'
More on Modules
from fibo import fib, fib2
fib(30) # 0 1 1 2 3 5 8 13 21
print(fib2(30)) # [0, 1, 1, 2, 3, 5, 8, 13, 21]
from fibo import * # except beginning with underscore
fib(30) # 0 1 1 2 3 5 8 13 21
print(fib2(30)) # [0, 1, 1, 2, 3, 5, 8, 13, 21]
import fibo as fib
fib.fib(30) # 0 1 1 2 3 5 8 13 21
print(fib.fib2(30)) # [0, 1, 1, 2, 3, 5, 8, 13, 21]
from fibo import fib as fibonacci
fibonacci(30) # 0 1 1 2 3 5 8 13 21
- For efficiency reasons, each module is only imported once per interpreter session.
- Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use
importlib.reload()
e.g.import importlib; importlib.reload(modulename)
Executing modules as scripts
python fibo.py <arguments>
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
python fibo.py 30 # # 0 1 1 2 3 5 8 13 21
The Module Search Path
- When a module named
spam
is imported, the interpreter first searches for a built-in module with that name. - These module names are listed in
sys.builtin_module_names
- If not found, it then searches for a file named
spam.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 no file is specified)
PYTHONPATH
- a list of directory names, with the same syntax as the shell variablePATH
.- The installation-dependent default (by convention including a
site-packages
directory, handled by thesite
module) - After initialization, Python programs can modify sys.path.
- The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path.
- This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended.
“Compiled” Python files
Standard Modules
import sys
sys.path.append(".")
dir()
Function
- used to find out names a module defines
import fibo, sys
dir(fibo) # ['__name__', 'fib', 'fib2']
dir(sys)
Packages
- structuring module namespace by using “dotted module names”
- module name A.B
- designates a submodule named B in a package named A
- Design a collection of modules (a “package”) for the uniform handling of sound files and sound data.
- Different sound file formats - .wav, .aiff, .au, so
- Different operations - mixing, adding echo, applying an equalizer function, creating an artificial stereo effect
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 on sys.path looking for the package subdirectory
- The $__init__.py$ files are required to make Python treat directories containing the file as packages.
- This prevents directories with a common name, such as string, unintentionally hiding valid modules that occur later on the module search path.
- In the simplest case, $__init__.py$ can just be an empty file, but it can also execute initialization code for the package or set the $__all__$ variable
import sound.effects.echo
sound.effects.echo.echofilter(input,
output,
delay=0.7,
atten=4)
from sound.effects import echo
echo.echofilter(input, output, delay=0.7, atten=4)
from sound.effects.echo import echofilter
echofilter(input, output, delay=0.7, atten=4)
Importing * From a Package
from sound.effects import * # will import all
- importing all can be time-consuming but can be defined what is included in $__all__$
__all__ = ["echo", "surround", "reverse"]
- If
__all__
is not defined, the statement fromsound.effects import *
does not import all submodules from the packagesound.effects
into the current namespace; it only ensures that the packagesound.effects
has been imported (possibly running any initialization code in__init__.py
) and then imports whatever names are defined in the package. - This includes any names defined (and submodules explicitly loaded) by
__init__.py
. - It also includes any submodules of the package that were explicitly loaded by previous import statements.
import sound.effects.echo
import sound.effects.surround
from sound.effects import *
Intra-package References
from . import echo
from .. import formats
from ..filters import equalizer