Sitemap
kailaspsudheer

kailaspsudheer

I am an AI engineering undergraduate. I am here to share my learnings and insights...........hope it's helpful :)

Python Package Development

Project structure, versioning, and Twine — Build and Publish a Python Package to PyPI

18 min readDec 14, 2025

--

Packaging Python code is one of the most effective ways to share ideas, standardize workflows, and build on past work. Learning to develop small, simple packages in Python helps a lot in understanding how larger complex frameworks are structured and built. The broader process of creating a robust, maintainable, and well-engineered package helps in understanding software engineering methodologies and best practices. In this article will examine the entire end-to-end process of creating and releasing Python packages, including local builds, Twine publishing, and the use of contemporary pyproject.toml. From code to PyPI!!

Pic by Chris

In day-to-day development, seemingly “small” packages from GitHub often become mission-critical: from a simple XML-to-CSV converter to advanced libraries like LLaMA-Factory, for efficient training and fine-tuning of LLMs. Understanding how these packages are built makes it easier to navigate their codebases, locate core functionality, and adapt them to real-world needs. Oftentimes I end up needing to refactor the code in these packages to fit my use cases, especially when doing research and development, as there won’t be a perfect ready-made solution to my problems. In this guide, we’ll see the steps behind building and publishing PyMailkit, a lightweight Python library I created for sending and receiving emails. Along the way, we’ll cover structure, metadata, builds, testing, and publishing, so the same workflow can take any idea from a local module to a package on PyPI.

TL;DR: The next section introduces how email workflows are handled in Python and provides a brief overview of the pymailkit package. It then walks through the Python packaging flow, detailing each step in modern package development. Along the way, it contrasts legacy practices with current standards — for example, moving configuration from setup.cfg to pyproject.toml. The section concludes by explaining build artifacts (such as wheels) and highlighting how packaging practice reinforces core software engineering principles.

Python Emails in Brief.

Packaging email functionality is a great example of turning a repeatable workflow into a reusable library and that is, partly my motivation to start with it. Python’s built-in smtplib creates an SMTP client session that can send mail to any server with an SMTP/ESMTP listener. This allows us to receive and send email messages from a python program. In order to connect with the Gmail account it’s advisable to set an app password. Gmail prefers an app‑specific passwords or a separate development account to avoid exposing primary credentials. This app‑specific password can be used to authenticate the connection to Gmail from any Python scripts. Here is a simple guide from the University of Maryland to set up an app password. For more details on sending emails using python, visit this blog by Real Python. Now we have some idea how mails work in python, let’s look into an example from PyMailkit package where just few lines of code that fetches emails from our inbox into a python list.

Press enter or click to view image in full size
Example to fetch 3 emails from your inbox using PyMailkit

That’s a huge reduction in boilerplate code you write, and also it’s free!!. These boilerplate code blocks become repetitive across projects; packaging them into a small, well‑tested library standardizes security and reduces overhead and errors. Say you’re developing a chatbot that needs access email functionality; you can use PyMailkit rather than writing 100s of lines of code and maintaining a separate class file for your projects.

PyMailkit can expose a simple receive() helper that authenticates and returns normalized results (from, subject, text body, and attachments) all while keeping secure defaults and wrapping them into a clean library.

That being said let’s now see how we can package code in python and publish it as a library in PyPI.

The python packaging flow

Publishing a package requires a ‘packaging flow’ from the author’s code directory to the user’s environment. A packaging flow is the end‑to‑end path that takes a local codebase and turns it into an installable, versioned artifact that others can discover, install, and use with a single command, like pip install . In practice, this means moving from a clean project structure and clear metadata to reproducible builds, local testing and validation, then finally publishing to an index like PyPI. The python packaging flow requires a series of steps that are :

  • Start with a clean source tree : Organize your project in specific folders and setup essential things like Git and mandatory files like LICENSE, README.md, pyproject.toml (a more modern config file), and optionally setup.cfg.
  • Prepare the configuration file : The configuration file acts like a blueprint of your package. It contains metadata (name, version, description, authors, license, URLs), dependencies, and the build backend. Here we use the modern pyproject.toml as our configuration file. The build backend we choose in this file (like setuptools, Hatchling, or Poetry ) is then used to generate distribution archive files in the next step.
  • Build distribution artifacts: PyPI is not a code repository, we need to build distribution archives from our code and upload them. These archives are typically of tar.gz file formats. Python build backends generate sdist or wheel files from our source code, which we will see in detail in the coming sections.
  • Install the builds locally and test: Once we have the code in and the build ready, we can install the build locally and test it. Testing the package locally will help rectify any issues found after the build. Install the builds in the local environment to validate imports and basic usage.
  • Add user‑facing docs and licensing: Ensure legal and user‑facing metadata are complete, LICENSE and README.md should be present and properly referenced in our repository and also in PyPI.
  • Upload the artifacts to PyPI : Upload the build artifacts to PyPI (or to TestPyPI for a dry run) using Twine, a utility for publishing Python packages on PyPI. Developers can download the package and install it via the pip install command.

1. A Clean Source Tree.

The first step in building any package is to create a source tree with all the files and folders structured and organized in one place. We need to pick a unique name for our package and name the root directory after it. The root directory should contain a src/ directory which where all the code should go in . The src/ is the core of the package and that’s where we run all the commands and tests. This is followed by a tests/ directory where all the tests scripts goes in. Finally all the other essential files like LISCENCE, README.md, pyproject.toml, setup.py or setup.cfg should be organized as shown below.

package_name/
├── docs/ # We can add readme.md to the docs if needed.
├── scripts/ # Additional shell or python scripts (if any).
├── src/
│ ├── package_a/
│ │ ├── __init__.py
│ │ └── module_a.py
│ └── └── module_b.py
├── tests/
│ ├── __init__.py
│ ├── test_module_a.py
│ └── test_module_b.py
├── LICENSE.txt
├── CHANGES.txt # This one is optional for small projects.
├── MANIFEST.in # This one is optional for small projects.
├── README.txt
├── pyproject.toml
├── setup.py # Not nessesary to have both setup.py & pyproject.toml.
└── setup.cfg

As you see in the diagram , couple of those files and directories are mandatory while others are optional. Python expects us to have a LISCENCE file, a config file (pyproject.toml ,setup.py, setup.cfg) a src/ directory and a README.md file.

It is not mandatory to have a MANIFEST.in which is to keep track of additional files and a CHANGES.txt which keep track of changes made to the package over time. Unless your package is very huge and versatile you don’t need both. We technically only need one of the config files but we’ll talk more about that and the difference between them in the next section Prepare the configuration file.

Now in the case of a simple lightweight package like PyMailkit we can keep the mandatory files alone and have a simple build, since we’re focused only on very few functionality. Here is the directory structure for PyMailkit

PyMailkit/
├── LICENSE
├── pyproject.toml
├── README.md
├── setup.py
└── src/
└── └── pymailkit/
├── ├── __init__.py
├── ├── auth.py
├── ├── receiver.py
├── ├── sender.py
└── └── tests/
├── ├── test_receiver.py
└── └── test_sender.py

We have the LISCENCE, README.md, the config files pyproject.toml and the setup.py . There is a src/ directory and inside that is the tests/ directory containing the tests scripts. Find more about the package in the GitHub repo.

By this time, you would’ve noticed the file __init__.py . This is a special file in python that mark a directory as a python package. The __init__.py file tells the python interpreter that the current directory should be treated as a package. The__init__.py defines namespaces and packages and is executed when the package is imported. It helps in ordering and organizing the imports of classes or functions from the package. Given below is the __init__.py from PyMailkit package.

Press enter or click to view image in full size
The __init__.py file from PyMailkit.

The code defines relative imports for EmailSender , EmailRecevier and authenticate classes which helps optimize imports, we can now import these classes directly using from pymailkit import EmailSender . We can also define static data like version, author and email these are accessible when we import the package. The __all__ variable is to specify which modules or names should be imported when using the wildcard (*) import, in case we use from pymailkit import * Then, it imports the specified submodules within the current package using relative import syntax. Now let’s see what are the config files and how we can prepare them.

It’s important to understand the difference between a module and a package. Module is a single python file containing classes, functions, variables etc. The purpose of a python module is organizing small projects and simple code reuse where we import classes directly using import module. A package on the other hand is more of a directory containing multiple modules and code files ( sub packages ). The purpose is to Organizing large projects, code reuse. It is imported via import package.module .

2. Prepare the configuration file.

Once we have the source code ready, next we need to create a configuration file. A configuration file acts as a blueprint of a package, it lays down lot’s of information centered around the packages. It tells python what build backend to use, declares package name, package version, description, authors, license, URLs, Python release version, and additional dependencies. Python earlier used to have setup.py as it’s primary configuration file format, later came the setup.cfg . These where then replaced with the modern pyproject.toml configuration file with the arrival of new dependency management and packaging tools like Poetry.

Nowadays it’s recommended to have pyproject.toml as the primary configuration file used for packaging while setup.py acts as as a supplementary material. TOML is a markup language which is s human-readable data serialization format designed for configuration files like pyproject.toml. We organize the file in key-value pair format and refer to each section or key as table. There should be these 3 important tables in pyproject.toml when building a package.

  1. The [build-system] table which tells the package installing tool which build backend to use.
  2. The [project] table is the format that most build backends use to specify all of your project’s basic metadata, such as the dependencies, author name, etc. This would be the largest table.
  3. The [project.urls] table contains the URLs associated with your project, displayed on the left sidebar of your PyPI project page.

The [build-system] table contains a build-backend key, which specifies the build backend to be used. It also contains a requires key, which is a list of dependencies needed to build the project — this is typically just the build backend package, but it may also contain additional dependencies. We will use the setuptools build backend which is already integrated into the PyPI ecosystem and it’s not a 3rd party dependency.

[build-system]
requires = ["setuptools >= 77.0.3"]
build-backend = "setuptools.build_meta"

A build backend is a Python package that implements standardized interfaces for building and installing Python packages. The rest of the pyproject.toml will contain more information on the [projects] table and it’s subheadings. The [projects] table is the central aspect of the config file which we will cover shortly. For reference i’ve pulled up the entire pyproject.toml file from PyMailkit, here is how to organize a full config file.

Press enter or click to view image in full size
A full pyproject.toml file.

As you would notice, the [project] table has plenty of keys we will discuss them one by one.

About the project table

  • The name : is the name of your project on PyPI. This field is required and is the only field that cannot be marked as dynamic the name should be ASCII code, no hyphen, dot and all.
  • The version : Marks the version number, you can add a tag as dynamic and let the let your build backend compute the metadata for you. Like for version it would pick up the value from __version__ tag in GitHub.
  • The description : It should be a one-line description of your project, to show as the “headline” of your project page on PyPI.
  • The readme is a longer description of your project, to display on your project page on PyPI. This is basically pointing towards the readme.md file which will be renderd on PyPI homepage.
  • We need to Pick a valid license and put it under that tag, have a LISENCE file for that.
  • keywords : This will help PyPI’s search box to suggest your project when people search for these keywords.
  • The authors tag keep the name and email address of the authors and the maintainers.
  • classifiers : A list of PyPI classifiers that apply to your project. Although the list of classifiers is often used to declare what Python versions a project supports, this information is only used for searching and browsing projects on PyPI, not for installing projects. To actually restrict what Python versions a project can be installed on, use the requires-python tag.

If your project has dependencies, you may list them like this:

[project]
dependencies = [
"httpx",
"gidgethub[httpx]>4.0.0",
"django>2.1; os_name != 'nt'",
"django>2.0; os_name == 'nt'",
]
[project.optional-dependencies]
gui = ["PyQt5"]

You may want to make some of your dependencies optional, In that case, put them in optional-dependencies . These extras can be installed by using the pip command pip install your-project-name[gui] .

Get kailaspsudheer’s stories in your inbox

Join Medium for free to get updates from this writer.

The [tool.setuptools] table (Optional): While much of the configuration is handled by the [project] table, Setuptools also allows for specific configurations within a [tool.setuptools] sub-table. This is used for more advanced or Setuptools-specific settings that are not covered by the standard [project] table. setup.py is still needed as supplementary to pyproject.toml for package discovery. The setup.py, later it’s modern version setup.cfg, was the configuration file used and they are still valid today . If some programmatic configuration is needed (such as building C extensions), keeping setup.py in our project helps a lot.

Press enter or click to view image in full size
The setup.py from pymailkit.

I used setup.py to let the build backend know where my source code sits, since my source tree was little different from the standard one. We can always have setup.py instead of pyproject.toml. A lot of older python libraries still uses the setup.py file.

Now as the blueprint is ready we can move on to generating distribution artifacts that are to be uploaded into PyPI. The next section covers building distribution artifacts from the source code using the config file we created.

To sum it up, the recommended configuration file is pyproject.toml. This file has largely replaced setup.py and setup.cfg for most common use cases.

3. Build the distribution artifacts.

It’s time to create the distribution artifacts after selecting a build backend and setting up the pyproject.toml configuration file. We have to convert our code into distribution formats that can be consumed by python. When we install packages from PyPi, it’s not the code that we are downloading, it’s actually these build distributions. For example you would’ve noticed these artifacts being downloaded when we run any pip install command.

Press enter or click to view image in full size
When we install packages, we see these .whl files are downloading.

As you see in the image, the green marker points to the file numpy-2.3.2-cp311-cp311-win_amd64.whl (13.1 MB) which is a wheel file, sometimes known as Built Distribution. Python wheels are a pre-built binary package format for Python modules and libraries. These wheel files can be downloaded and installed fast without the need to compile the package from source code. Python wheels can be platform- and Python-version-specific. We first download a source distribution (typically .tar.gz) that includes project source and metadata. The installers will build a wheel from it during the installation. A built distribution (.whl file ) contains exactly what gets installed. When building and publishing packages we generate and upload both these artifacts, both the tar.gz file and .whl file.

One of the key advantages of using wheels is that they allow Python modules to be installed and used without requiring a build process. This means that users can simply download a wheel package and install it using the pip command, without needing to compile the package from the source code or install any additional dependencies. To find more information on Wheel have a look at this post.

To generate these artifacts we need to navigate to the \src directory and run the command py -m build . There is one thing to be noted that the wheels follow a naming convention which includes information like the version, the platform and so on as shown below.

# the path to \src directory in the project
cd path_to_your_src_directory

# The command for generating distribution archives
py -m build

#Wheel file naming conversion
{distribution}-{version}-{build}-{python}-{abi}-{platform}.whl

Once we run this command, a dist/ directory is created and the archives are stored in them. The files are generated as shown in below.

Press enter or click to view image in full size
Build successful.

The pymailkit-2.0.1.tar and pymailkit-2.0.1-py3-none-any.whl are the Source Distribution and the Build Distribution files generated successfully from the py -m build command. The Source Distribution, also known as sdist, is used by the installers to build a wheel from it during installation. This enables building on any platform but requires build tools on the target machine. During the build process we need to specify what wheel we need according to our target platform. For macOS the wheel file name would end with macosx_10_13_x86_64.whl .

Together the Source Distribution and Built Distribution, are the two distribution artifacts in Python. Earlier we used to generate sdist and wheels separately using setup.py using commands $python setup.py sdist and $python setup.py bdist_wheel now both are handled using a single py -m build command.

4. Install the builds locally and test.

Normally when you install using pip it copies the code into the python site distribution and it get’s installed there. When working on our project we don’t want that, we want to install our package in our local src directory to work with it and test locally itself. Hence after building the wheel you run the python3 -m pip install -e . command. The pip command-line flag -e is short for --editable, and . refers to the current working directory.

Press enter or click to view image in full size
local installation of the package.

So every time you change your pyproject.toml or source code you run the build again and then install the artifacts locally using the command above. This to see if the package get’s installed correctly and you can perform local testing before uploading the package to PyPI. This allows for an error free release of our package, it’s better to find bugs at this stage than after release.

Press enter or click to view image in full size
Testing

Now the code is under src directory so if we can’t import the code in the current directory yet. You can install a project in “editable” or “develop” mode while you’re working on it. When installed as editable, a project can be edited in-place without reinstallation: changes to Python source files in projects installed as editable will be reflected the next time an interpreter process is started. Lastly, if you don’t want to install any dependencies at all, you can run: python3 -m pip install -e . --no-deps

Installing the built artifacts in the /dist directory (not the source directory) locally is very important for us to run tests before we upload the package. This can help us validate imports and basic workflows, fix any missing files, scripts, or dependency issues discovered at this stage . Most of the tests are written using the framework Pytest, once we have the test scripts ready we install the build and run pytest -s. The -s flag is for any user input that’s needed which can we passwords, API keys etc.

5. Add user‑facing docs and licensing.

Last but not least, write a concise README.md that includes installation, a quick start, and basic usage. Ensure LICENSE matches the classifier in pyproject.toml and is included in the source distribution. Use AI tools to rewrite readme, for less experienced folks it’s helpful to have a professional looking readme and other setup.

Don’t go in blindly with the AI writing docs because of the hallucinations it can invent features….it wrote about sending mails from Yahoo server for me ( I don’t have yahoo configured in my package code ). Always good to cross check.

5. Upload the artifacts to PyPI.

Finally it’s time we upload the build artifacts to the distribution system, which is PyPi for us. There is also an option to upload the built artifacts to TestPyPI to verify the metadata, how README rendering in the website and also test how our package is installing from a public index.

To upload the package we need to make use of a command-line utility called Twine , used by Python developers to securely upload packages to the Python Package Index (PyPI). Install twine if it is not present in the system, later use twine upload command.

$pip install twine

$twine upload dist/*

# This will prompt an anuthentication
username: USER
password:

You can upload your distributions to TestPyPI using twine by specifying the repository flag as shwon below:

$twine upload --repository testpypi dist/*

You can see if your package has successfully uploaded by navigating to the URL https://test.pypi.org/project/<sampleproject> where sampleproject is the name of your project that you uploaded. It may take a minute or two for your project to appear on the site : https://test.pypi.org/.

As mentioned in the build artifacts section, we upload the artifacts to PyPI not the source code or repository as it is. Once the upload is successful you’ll see the link to the PyPI page as shown in the image below.

Press enter or click to view image in full size
Upload Successful

Versioning : If there are changes to the code and you want to push the changes, you need to run another build process. That require editing the version in the pyproject.toml and generating new artifacts with the new version number. The example above have two artifacts with two versions because i didn’t clear the dist/ directory. Always clear the dist/ directory if you want to push only the latest.

Press enter or click to view image in full size
The package homepage in PyPI

I uploaded directly to PyPI as i was confident about my code and the fact that it’s a small package. For more complex, versatile packages it might be better to upload it to TestPyPI and performing tests after installing from the index. This help us understand how our library behave when other devs would be using it.

Conclusion.

Python package development is a fundamental aspect of modern software engineering, particularly within the Python ecosystem. It involves structuring and organizing Python code into reusable units (packages) that can be easily shared, distributed, and integrated into larger applications.
The Python package development follows a lot of fundamental software engineering practices. Modularity and interfaces: Packaging code into cohesive modules with clear APIs strengthens separation of concerns and supports reuse and maintainability across projects. Dependency Management: Software engineering often involves managing complex dependencies between various components. Python package managers like pip, Poetry, Hatch, and PDM enable efficient management of external libraries and packages required by a project, ensuring consistent environments and resolving dependency conflicts. Distribution and Sharing: Packages are the primary mechanism for distributing Python code to other developers or users. Tools like setuptools and build backends (e.g., wheel) are used to create distributable archives (e.g., .whl files) that can be uploaded to repositories like PyPI (Python Package Index) for easy installation. Testing culture: Integrating unit/integration tests and even BDD-style specifications cultivates habits that reduce defects and clarify requirements early. Documentation: Well-documented packages are essential for usability and maintainability. Tools like Sphinx can be used to generate comprehensive documentation from code comments and reStructuredText or Markdown files within the package structure. Standardization and Best Practices: Adhering to Python packaging standards (defined by PEPs — Python Enhancement Proposals) ensures compatibility and ease of use within the broader Python community. This includes conventions for package structure, metadata, and build processes.

In essence, Python package development is not just about writing code but about applying sound software engineering principles to create, manage, and distribute reusable and maintainable Python components. Learning to build Python packages is a practical pathway to mastering core software engineering principles.

References:

  1. Mark Smith — Publish a (Perfect) Python Package on PyPI [old way of doing it ]: https://www.youtube.com/watch?v=-WDV0-OB4fE
  2. Packaging Python Projects [the modern approach]: https://packaging.python.org/en/latest/tutorials/packaging-projects/
  3. What is __init__.py file in python and how to use it : https://realpython.com/python-init-py/
  4. Details on how to send emails via python: https://realpython.com/python-send-email/
  5. AI chat tools like Claude, Perplexity, ChatGPT are of tremendous help in developing packages in python, from wirting good docs in README.md to writing pytest functions.

--

--

kailaspsudheer
kailaspsudheer

Written by kailaspsudheer

I am an AI engineering undergraduate. I am here to share my learnings and insights...........hope it's helpful :)