Python Package
Python package actually is a folder or directory that have a file called __init__.py, and this folder can have many module (Python file that include function, class, ...).
So, basically Python package can be considered as a module.

Create a python package
- Create a directory / folder, (ex:
my_package) - Create a empty python file,
__init__.py - Create a 2 module, (ex:
add.pyfor function add;minus.pyfor function minus) - Create a function of add and minus.
my_package/add.py
py
def add(x, y):
return x + ymy_package/minus.py
py
def minus(x, y):
return x - yImport a python package & Usage
- Method of import a python package: Click here
- Create a main python file (must outside of the python package), (ex:
package_test.py)
package_test.py
py
from my_package.add import add
from my_package.minus import minus
print(add(1, 2))
print(minus(1, 2))Output:
3
-1__all__ for python package
We can
restrict the import everything(from module import *) of a python package, by define a__all__variable, it's almost same as the way of create a__all__variable to a module.But for the python package the place of define is slightly different from a module, For
modulewe define the__all__variable on thefile of the module, Whilepython packagewe will define it on__init__.pyfile.
INFO
__all__will only affect the import everything, fornormal importitwon't be affect.- Only the item in the list of
__all__variable are able to use whenimport everything
my_package/__init__.py
py
__all__ = ["add"]Example
test_all_var_package.py
py
from my_package import *
add()
minus() # Minus is not define