Python Notes and Examples

Modules and Packages

Modules are usally named lowercase, possibly including underscores, and correspond to filenames (module foo is imported from foo.py).

Importing a module in the usual way does so only once. Repeated importing just looks the module up in sys.modules.

To re-import a module, do import importlib then importlib.reload(the_mod).

sys.modules is a dict of currently-loaded/imported modules (the module name (string) → the module object).

import looks in sys.path for locations from which to load modules, the cwd being the first entry.

Within a module that has been imported, the global __name__ variable is that module’s name (a string), including the package (if any) it resides in. In the main script being run, __name__ equals “__main__”.

Note that you can always look at the __file__ global variable to see the name of the current module file.

Using your own local modules

To be able to import modules which you’ve placed in ~/pylib:

Packages

A package is a namespace for modules. Modules live in packages. Packages correspond with filesystem directories such that foo/bar/baz.py ↔ module foo.bar.baz (here, both foo and foo.bar are packages).

A module in package p can import another module the same pkg or below. For example, given:

From inside mod1.py, you can do:

Installing modules

For system-wide modules, use apt.

For your own venvs (see the venvs chapter), use that venv’s pip.

Packaging

See the Python Packaging User Guide by the illustrious Python Packaging Authority. PyPA repos are at https://github.com/pypa.

Legacy: eggs, easy_install