What are Python packages?
A Python package is a collection of modules.
Modules that are related to each other are mostly placed in the same package. When a module from an external package is required in a program, that package can be imported and its modules can be used.
For example, in a computer, files are stored in hierarchical structures for better organization and easy access. Similar files are stored in the same folder (for instance, all photos might be stored in the "photos" folder).
Similarly, Python has packages for directories and modules for files.
How to create a Python package?
A package is a directory of Python modules that contains an additional __init__.py file, which distinguishes a package from a directory that should contain multiple Python scripts.
For example, let's create two modules, module1.py and module2.py, in the same directory called my-package.
def foo():
print('module1 - foo()')
class Foo:
passdef bar():
print('module2 - bar()')
class Bar:
passIt's done! You have created a package with two modules!
Visual representation what we have done is the following:
my-package/
├── module1.py
└── module2.pyPackage Initialization
If a file called __init__.py is present in a package folder, it is invoked when the package or a module of the package is imported.
For example:
print(f'Invoking __init__.py for {__name__}')
NAMES = ['Tom', 'Ryan', 'John']and then do the import:
import my-package
# Invoking __init__.py for my-package
print(my-package.NAMES)
# ['Tom', 'Ryan', 'John']How to import modules from a package?
Modules from packages can be imported using the dot (.) operator and the import keyword:
import <module_name>[, <module_name> ...]
import my-package.module1, my-package.module2You can import all objects from a module using from my-package import *:
from <module_name> import *
from my-package.module1 import *You can import only the function (or class or variable) required by a module within a package:
from <module_name> import <name(s)>
from my-package.module1 import FooDuring import, it is possible to assign an alternate name to the imported object, as follows:
from <module_name> import <name> as <alt_name>
from my-package.module1 import Foo as FooAliasSubpackages
Packages may contain nested subpackages, with arbitrary depths.
For example:
my-package/
├── sub-package1/
│ ├── module1.py
│ └── module2.py
└── sub-package2/
├── module3.py
└── module4.py