Python modules can be organized into packages. A package is a namespace which contains a set of modules. Packages are useful for organizing modules, especially when an application is large and contains a lot of modules. To create a package, create a directory and add python files to it. The directory must contain an __init__.py file in order to be recognized as a package.
Example:
pkg1
__init__.py
mod1.py
mod2.py
app.py
Modules, which are part of a package, can then be imported using the dot notation:
import pkg1.mod1
Modules can also be imported as follows:
from pkg1 import mod1
Specific module members can be directly imported:
from pkg1.mod1 import do_something
or
from pkg1.mod1 import do_something as do
The __init__.py file defines package initialization code. It can be empty or define a list of modules which are imported on initialization. This can be done individually:
import pkg1.mod1
import pkg1.mod2
or using __all__ to define a list of modules to import:
__all__ = [“mod1”, “mod2”]
Using
from pkg1 import *
would then import mod1 and mod2 at once.
Packages can contain subpackages by creating sub directories:
pkg1
__init__.py
subpkg1
__init__.py
mod1.py
mod2.py
subpkg2
__init__.py
moda.py
modb.py
moda would be imported as:
import pkg1.subpkg2.moda
Each subpackage also needs to contain in __init__.py file, which may or may not be empty.
Full Example:
app.py:
import pkg1
from pkg1 import mod2
pkg1.mod1.print_mod_name()
mod2.print_mod_name()
pkg1/__init__.py:
import pkg1.mod1
import pkg1.mod2
pkg1/mod1.py:
def print_mod_name():
print(‘Mod 1’)
pkg1/mod2.py:
def print_mod_name():
print(‘Mod 2’)
Leave a Reply
You must be logged in to post a comment.