Modules and Packages#
Modules#
Collection of … well … objects - e.g. classes, functions, variables
Collected in a dedicated
.pyfilePulled in with the
importstatement
import sys
So where is sys looked for?
In the directory where the importer lives
Along the
PYTHONPATHenvironment variableIn the Python installation’s module directories
Modules are Objects#
importmakes a module object available under a name⟶ a variable
Contained names accessible through that variable
⟶ “Namespace”
import sys
...
sys.exit(42)
Other Forms (1)#
from sys import exit
exit(42)
from sys import *
exit(42)
Pulls in everything into the importer’s namespace
Well, except those names that start with an underscore
Conflicts easily possible
Importer’s names are overwritten with conflicting names
Other Forms (2)#
import sys
my_sys = sys
del sys
import sys as my_sys
from sys import exit as my_exit
my_exit(42)
Packages#
Package: collection of modules (and further packages)
“Subnamespace”
import os.path
path = os.path.normpath('a/../b')
from os.path import normpath
Executing Modules as Scripts#
A module’s name is its filename, with the
.pyextension strippedAvailable to the module in the variable
__name__Can be used to decide if the module is being imported or executed as a script
mysupermodule.py#def mysuperfunction(a, b):
...
if __name__ == '__main__':
mysuperfunction(sys.argv[1], sys.argv[2]))
Package Structure#
package/
+-- __init__.py
+-- subpackage1
| +-- __init__.py
| +-- module1.py
| \- module2.py
\- subpackage2
+-- __init__.py
+-- module1.py
\-- module2.py
Top level directory
package/found in module search pathEach directory has file
__init__.pyDisambiguation
Usually empty
Relative Imports (1)#
package/
+-- subpackage1
+-- module1.py
\- module2.py
Problem: inside module1.py, I want to …
import module2Not search along the entire module search path
I know that
module2is next to me
from . import module2
Relative Imports (2)#
package/
+-- subpackage1
\-- module1.py
\- subpackage2
\-- module1.py
Problem:
subpackage1/module1.pywants to importsubpackage2/module1.py… and nothing else
from ..subpackage2 import module1