DEV Community

Abhi Dadhaniya
Abhi Dadhaniya

Posted on

Build your own python package easily

Build your own python package

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:

  1. Create a directory for your project:
 mkdir the-good-stuff && cd the-good-stuff 
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a Git repository:
 git init 
Enter fullscreen mode Exit fullscreen mode
  1. Create essential files and folders:
 touch README.md mkdir src tests 
Enter fullscreen mode Exit fullscreen mode
  1. Folder structure should look like this:
 the-good-stuff/ ├── README.md ├── src/ │ └── the_good_stuff/ │ └── __init__.py └── tests/ 
Enter fullscreen mode Exit fullscreen mode

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:

  1. Install Poetry using pip:
 pip install poetry 
Enter fullscreen mode Exit fullscreen mode
  1. Initialize your package:
 poetry init 
Enter fullscreen mode Exit fullscreen mode

Answer the prompts to set up your project metadata such as package name, version, author, license, description, and dependencies.

  1. 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" 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode
  • For development dependencies (like linters or test frameworks):
 poetry add pytest --group dev 
Enter fullscreen mode Exit fullscreen mode

Run all commands within a virtual environment:

poetry shell 
Enter fullscreen mode Exit fullscreen mode

Yep, no pip install or requirements.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] 
Enter fullscreen mode Exit fullscreen mode

src/the_good_stuff/*init**.py:*

from .utils import DateUtils, StringUtils __all__ = ["DateUtils", "StringUtils"] 
Enter fullscreen mode Exit fullscreen mode

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" 
Enter fullscreen mode Exit fullscreen mode

Run tests with:

pytest 
Enter fullscreen mode Exit fullscreen mode

Bonus: Add automated tests for confidence before every release.


Packaging and Publishing

Finally, it’s time to package and publish your masterpiece!

Local Installation

  1. Build the package:
 poetry build 
Enter fullscreen mode Exit fullscreen mode
  1. Install the package locally using pip: Using absolute path:
 pip install /absolute/path/to/the-good-stuff 
Enter fullscreen mode Exit fullscreen mode

Using relative path:

 pip install ../path-to/the-good-stuff 
Enter fullscreen mode Exit fullscreen mode

⚠️ 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")) 
Enter fullscreen mode Exit fullscreen mode

Publishing to a Private Repository

Configure the private repository in Poetry:

 poetry config repositories.my-private-repo https://my-repo-url.com 
Enter fullscreen mode Exit fullscreen mode

Publish your package:

 poetry publish --repository my-private-repo 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

Tip: Always use secure repositories for sensitive or internal code.


Version Management

Poetry makes versioning simple:

  • Bump the patch version:
 poetry version patch 
Enter fullscreen mode Exit fullscreen mode
  • Bump the minor version:
 poetry version minor 
Enter fullscreen mode Exit fullscreen mode
  • Bump the major version:
 poetry version major 
Enter fullscreen mode Exit fullscreen mode

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)