How to Create a Python Package: Step-by-Step Guide
To create a Python package, organize your code in a folder with an
__init__.py file, add your modules, and create a setup.py file to define package metadata. Then, use python setup.py sdist to build the package for distribution.Syntax
A Python package requires a folder with an __init__.py file to mark it as a package. The setup.py file contains metadata and instructions for building and installing the package.
package_name/: Folder containing your package code.__init__.py: Empty or initialization code file inside the package folder.setup.py: Script with package info like name, version, and modules.
plaintext
package_name/
__init__.py
module1.py
setup.pyExample
This example shows a simple package named mypackage with one module and a setup.py file to build it.
python
mypackage/
__init__.py
greetings.py
# greetings.py
def say_hello(name):
return f"Hello, {name}!"
# setup.py
from setuptools import setup, find_packages
setup(
name='mypackage',
version='0.1',
packages=find_packages(),
description='A simple greeting package',
author='Your Name',
author_email='your.email@example.com'
)
# Usage example after installation
# from mypackage.greetings import say_hello
# print(say_hello('Alice'))Output
Hello, Alice!
Common Pitfalls
Common mistakes include:
- Missing
__init__.pyfile, so Python does not recognize the folder as a package. - Incorrect or missing metadata in
setup.py, causing installation errors. - Not using
setuptoolsinsetup.py, which is the modern standard. - Forgetting to build the distribution before installing or uploading.
python
# Wrong: setup.py missing setuptools from distutils.core import setup setup( name='mypackage', version='0.1' ) # Right: use setuptools from setuptools import setup, find_packages setup( name='mypackage', version='0.1', packages=find_packages() )
Quick Reference
Steps to create and distribute a Python package:
- Create a folder with your package name.
- Add an
__init__.pyfile inside it. - Add your Python modules (.py files).
- Create a
setup.pyfile with package metadata usingsetuptools. - Build the package with
python setup.py sdist. - Install locally with
pip install .or upload to PyPI.
Key Takeaways
A Python package needs a folder with an __init__.py file to be recognized.
Use setuptools in setup.py to define package metadata and modules.
Build your package with python setup.py sdist before installing or sharing.
Always include clear metadata like name, version, and author in setup.py.
Test your package locally by installing it with pip before publishing.