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
reload(some_mod) importlib.
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).
're']
sys.modules[#=> <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
__file__ some_mod.
Also possibly of interest:
some_mod.__package__
some_mod.__version____name__ some_mod.
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
0, '/home/john/pylib') sys.path.insert(
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:
-proj.py
my/
my_proj# defines func f()
mod1.py # defines func g()
mod2.py /
pkg1# defines func h() mod3.py
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:
- distutils (deprecated, replaced by Setuptools)
- eggs (introduced by Setuptools, and replaced by Wheels)
- easy_install (introduced by Setuptools, and replaced by pip)
- Distribute (was a fork of Setuptools)
- Distutils2 (defunct)