Skip to content

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.

Python package explaination graph

Create a python package

  1. Create a directory / folder, (ex: my_package)
  2. Create a empty python file, __init__.py
  3. Create a 2 module, (ex: add.py for function add; minus.py for function minus)
  4. Create a function of add and minus.

my_package/add.py

py
def add(x, y):
    return x + y

my_package/minus.py

py
def minus(x, y):
    return x - y

Import 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 module we define the __all__ variable on the file of the module, Whilepython package we will define it on __init__.py file.

INFO

  • __all__ will only affect the import everything, for normal import it won't be affect.
  • Only the item in the list of __all__ variable are able to use when import 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

Minus is not define