Python Docs

Python Packages — Full Cheat Sheet

What is a Package?

A package is a collection of Python modules stored in a folder that contains a special file named __init__.py.

Packages help organize code into logical groups and allow code reuse across projects.

  • Modules = Single Python files
  • Packages = Folders containing modules
  • Libraries = Collections of packages

Package Structure

A package is simply a folder containing Python modules and an __init__.py file.

mypackage/
{
  __init__.py
  module1.py
  module2.py
}

__init__.py

This file makes Python treat the folder as a package. It can be empty or contain initialization code.

# __init__.py
print("Initializing my package")

Using a Package

Import modules inside a package using dot notation:

import mypackage.module1

To import a specific function:

from mypackage.module1 import myFunction

Installing Packages (Using PIP)

Install

pip install camelcase

List Installed Packages

pip list

Uninstall

pip uninstall camelcase

Creating Your Own Package

1. Create Folder Structure

Example folder structure:

mypackage/
{
  __init__.py
  module1.py
  module2.py
}

2. Add setup.py

This file tells Python how to build and install your package.

from setuptools import setup, find_packages

setup(
  name="mypackage",
  version="1.0.0",
  packages=find_packages(),
  install_requires=["requests"]
)

3. Build the Package

python setup.py sdist bdist_wheel

4. Install Locally (For Testing)

pip install .

Publishing Your Package to PyPI

1. Install Twine

pip install twine

2. Upload Package

python -m twine upload dist/*

Your package will now appear on pypi.org.

Best Practices for Packages

  • Use meaningful package and module names.
  • Keep functions small and modular.
  • Add documentation inside your package.
  • Include a README.md file.
  • Use semantic versioning (1.0.0, 1.0.1, etc.).
  • Avoid circular imports between modules.