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).

sys.modules['re']
#=> <module 're' from '/usr/lib/python3.4/re.py'>

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:

import sys
sys.path.insert(0, '/home/john/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:

my-proj.py
my_proj/
    mod1.py      # defines func f()
    mod2.py      # defines func g()
    pkg1/
        mod3.py  # defines func h()

From inside mod1.py, you can do:

from . import mod2        # Then call `mod2.g()`.
from .mod2 import g       # Call `g()` directly. Meh.
from .pkg1 import mod3    # Then call `mod3.h()`.
from .pkg1.mod3 import h  # Can call `h()` directly. Meh.

Installing modules

For system-wide modules, use apt.

If using pip (for “user-wide” packages), use:

python3 -m pip install --user {some-package}

This will install modules into ~/.local/lib/python3.xx/site-packages/.

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