Python Basics: Packages
Packages Introduction
Python packages are just a folder containing Python modules. Python packages just require an init.py file, often blank, inside of them to be recognized as a package. You can think of packages as a level up of organization from modules. Packages can even contain subpackages.
Importing Packages
To import packages, you use the import keyword to import the definitions in the package’s __init__.py or modules inside the package.
Dot notation is used to get to subpackages and definitions within modules.
my_package/
|
|___ __init__.py
|___ my_module.py
|______my_subpackage_1/
| |
| |___ __init__.py
| |___ my_submodule_1.py
|______my_subpackage_2/
|
|___ __init__.py
|___ my_submodule_1.py
# Imports definitions my_package's from __init__.py
import my_package
# Imports the definitions in my_module
import my_package.my_module
# Imports definitions from my_subpackage_1's __init__.py
import my_package.my_subpackage_1
# Imports my_module into the namespace
from my_package import my_module
# Imports my_submodule_1 into the namespace
from my_package.my_subpackage_1 import my_submodule_1
Creating your own Packages
Following the Python documentation on creating packages, we need to create a few files. The most important is setup.py, as it defines the metadata for our package. It includes things like author name, other libraries needed to install, and the package version. The sample package is linked here.
# setup.py
import setuptools
setuptools.setup(
name="PythonBasicsPackages",
version="1.0.0",
author="Me",
author_email="jamesheathradford@gmail.com",
description="Python Basics Package",
long_description="A sample package to demonstrate how pip installs user packages",
long_description_content_type="text/markdown",
url="https://github.com/JamesFHeath/jamesfheathblog_code/tree/master/Python%20Basics",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
)
Sample Package/
|
|___ setup.py
|______PythonBasicsPackages/
| |
| |___ __init__.py
| |___ sample_module.py
You simply install it by running pip install on the setup.py directory.
pip install /path/to/Sample Package/
Then you just import like any other package.
from PythonBasicsPackage import sample_module