Python Notes and Examples
 

Modules and Packages

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

Import a module like

import some_mod
import some_pkg.some_mod
from some_pkg.some_mod import foo
import some_pkg.some_mod as sm
from some_pkg.some_mod import foo as f

Repeated importing does not “re-import”, but rather just looks the module up in sys.modules. To re-import a module, do

import importlib
importlib.reload(some_mod)

sys.modules is a dict of currently-loaded/imported modules (the module name (string) → the module object, which includes the path to the module file).

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

So, to see from where (which module file) a module was imported, you could either look at sys.modules['some_mod'], or else do

import some_mod
some_mod.__file__

Also possibly of interest:

some_mod.__package__
some_mod.__version__
some_mod.__name__

During importing, import looks in sys.path for locations from which to load modules, with 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__”.

See also the inspect module.

Using your own local modules

To be able to import modules which you’ve placed in your own ~/pylib, do this first:

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), do:

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

This will install modules into ~/.local/lib/python3.xx/site-packages/. Note, if you accidentally leave out the --user, and you’re not root, then pip will default to user-wide.

Do not use pip as root unless you’re sure that’s what you really want.

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: