User Tools

Site Tools


programming:python:packaging

This is an old revision of the document!


Packaging

In Python, individual source files are referred to as modules. They represent a single collection of code, and can be imported. Packages are directories containing an __init__.py file and other modules. They are comparable to namespaces, and can also be imported.

Here's an example of a package containing modules:

my_package/
    __init__.py
    ui.py
    attribute.py
    model.py
    router.py

There are multiple ways to interact with a package, which are covered below. In every case, it's assumed that the Python interpreter is in the directory above my_package/.

Simple Importing

# Import just the package
import my_package

In this case, importing the package will process everything that's in __init__.py, including any pre-defined imports. It's considered good practice to define which modules get imported by default when importing a package, to ensure only the necessary modules are loaded. Your modules can individually import any part of the package they need to get the job done. To do this, your __init__.py should look somewhat like this:

__init__.py
# Let's say you only need the model and router to get started
from . import (model, router)

The . here means "the current package". If you have sub-packages, you can address them with a dot preceding its name, like .my_subpackage.

If every module is needed in your package, you can leave __init__.py as an empty file and Python will figure it out for you.

The same effect can be achieved using the __all__ variable:

__init__.py
# Overload the __all__ variable to hook into existing Python logic
__all__ = ["model", "router"]

Single Module Importing

Sometimes, you only need a single module from a package. That's easy:

# Import only the UI
from my_package import ui

In this example, only the ui module is imported. It gets injected into the current environment as ui, and you can access its members as well, using something like ui.create_box().

Single Member Importing

Lastly, sometimes you need only specific parts of a module. That's easy, too!

# Import only specific things from a given module
from my_package.router import do_route

In the above example, do_route will become available in the current environment, imported from the router module inside the my_package package. If you end up with name collisions, you can rename the import with the as keyword:

# Import with a different name
from my_package.router import do_route as make_route

References

programming/python/packaging.1532407493.txt.gz · Last modified: 2018-07-24 04:44 by zlg