Introduction
Have you ever wondered how developers turn their code into shareable Python packages? Maybe you've thought, "Why is packaging so complicated?" Don't worry—it’s not as scary as it sounds. In this blog, I'll guide you through the process of building and publishing a Python package using Poetry, a powerful dependency management tool.
By the end of this post, you’ll have a clear understanding of how to package your code, manage dependencies, and publish it locally or to a private repository.
Setting Up the Project
Every great package starts with a structured project setup. Here’s how you can kick things off:
- Create a directory for your project:
mkdir the-good-stuff && cd the-good-stuff
- Initialize a Git repository:
git init
- Create essential files and folders:
touch README.md
mkdir src tests
- Folder structure should look like this:
the-good-stuff/
├── README.md
├── src/
│ └── the_good_stuff/
│ └── __init__.py
└── tests/
Pro tip: Keeping your code under the
src/
directory helps avoid import issues later.
Configuring Poetry
Poetry simplifies dependency management and packaging for Python projects. Here's how to get started:
- Install Poetry using
pip
:
pip install poetry
- Initialize your package:
poetry init
Answer the prompts to set up your project metadata such as package name, version, author, license, description, and dependencies.
- Your
pyproject.toml
file should look something like this after setup:
[tool.poetry]
name = "the-good-stuff"
version = "0.1.0"
description = "A Python package for advanced utility functions"
authors = ["Your Name <your.email@example.com>"]
[tool.poetry.dependencies]
python = "^3.9"
[tool.poetry.group.dev.dependencies]
pytest = "^7.0.0"
Why Poetry? It handles dependency resolution like a champ, making version conflicts a thing of the past.
Managing Dependencies
Need external libraries? Poetry makes it effortless:
- To add a runtime dependency:
poetry add requests
- For development dependencies (like linters or test frameworks):
poetry add pytest --group dev
Run all commands within a virtual environment:
poetry shell
Yep, no
pip install
orrequirements.txt
chaos here.
Writing Core Functionality
Put your magic inside the src/the_good_stuff/
folder. Let’s create a utility module with intermediate examples:
src/the_good_stuff/utils.py:
import datetime
class DateUtils:
@staticmethod
def current_datetime():
"""Returns the current date and time."""
return datetime.datetime.now()
class StringUtils:
@staticmethod
def reverse_string(text: str) -> str:
"""Reverses the given string."""
return text[::-1]
src/the_good_stuff/*init**.py:*
from .utils import DateUtils, StringUtils
__all__ = ["DateUtils", "StringUtils"]
Remember: Clear, well-documented functions make your package more developer-friendly.
Testing the Package
No package is complete without testing. Let's use pytest
to validate our functionality:
tests/test_utils.py:
from the_good_stuff import DateUtils, StringUtils
def test_current_datetime():
assert DateUtils.current_datetime() is not None
def test_reverse_string():
assert StringUtils.reverse_string("hello") == "olleh"
Run tests with:
pytest
Bonus: Add automated tests for confidence before every release.
Packaging and Publishing
Finally, it’s time to package and publish your masterpiece!
Local Installation
- Build the package:
poetry build
- Install the package locally using
pip
: Using absolute path:
pip install /absolute/path/to/the-good-stuff
Using relative path:
pip install ../path-to/the-good-stuff
⚠️ Warning: Installing the package globally is recommended to avoid potential virtual environment conflicts.
Usage of Your Masterpiece
Here’s how you can use the package after installation:
from the_good_stuff import DateUtils, StringUtils
print("Current DateTime:", DateUtils.current_datetime())
print("Reversed String:", StringUtils.reverse_string("ChatGPT"))
Publishing to a Private Repository
Configure the private repository in Poetry:
poetry config repositories.my-private-repo https://my-repo-url.com
Publish your package:
poetry publish --repository my-private-repo
To install a package from a specific branch of a GitHub repo:
poetry add git+https://github.com/your-repo/the-good-stuff.git@branch-name
Tip: Always use secure repositories for sensitive or internal code.
Version Management
Poetry makes versioning simple:
- Bump the patch version:
poetry version patch
- Bump the minor version:
poetry version minor
- Bump the major version:
poetry version major
Tip: Stick to semantic versioning (
MAJOR.MINOR.PATCH
) for clarity.
Tips and Best Practices
-
Semantic Versioning: Stick to a versioning format like
MAJOR.MINOR.PATCH
. - Dependency Groups: Use development and production dependency groups for cleaner environments.
-
Documentation: Maintain a thorough
README.md
to help users integrate your package. -
Linting: Tools like
flake8
ensure your code follows best practices. - Security: Regularly audit dependencies to catch vulnerabilities.
Conclusion
We’ve walked through project setup, dependency management, testing, and publishing. Now, you have the tools to create polished, shareable Python packages. What’s next? How about refining your project or experimenting with more advanced features like custom entry points?
Got questions or ideas? Drop them in the comments below! Let’s keep learning together and help each other grow. Happy coding!
Top comments (0)