DEV Community

Srimathi10
Srimathi10

Posted on

How to Create and Upload a Python Package to PyPi: A Step-by-Step Guide

Creating and uploading a Python package to PyPi (Python Package Index) is an essential skill for sharing your work with the community. In this blog post, we’ll walk through the complete process using an example package, file_compressor, which compresses files into a .zip format. By the end of this guide, you’ll be able to create, build, and upload your own Python package to PyPi.

Let’s get started!


Step 1: Setting Up Your Environment

Before we begin creating the Python package, you need to set up your environment with the necessary tools. If you don't have Python installed, please install it from python.org.

We will also need a few packages to help build and upload the package:

pip install setuptools wheel twine
Enter fullscreen mode Exit fullscreen mode

What Are These Packages?

  • setuptools: A tool for packaging Python projects.
  • wheel: A packaging format for Python distribution.
  • twine: A tool to securely upload your package to PyPi.

Step 2: Create Your Package Directory

Now that you have the necessary tools, create a directory for your project. Inside this directory, you will organize your Python package and related files.

Here’s how your directory structure might look for the file_compressor package:

file_compressor/
├── file_compressor/              # Package directory containing the Python code
│   └── __init__.py               # Mark this directory as a Python package
├── setup.py                      # Metadata about the package
├── LICENSE                       # License information (MIT, GPL, etc.)
├── README.md                     # Documentation about your package
├── MANIFEST.in                   # Include additional non-Python files (optional)
└── tests/                        # Unit tests for the package
Enter fullscreen mode Exit fullscreen mode

Package Code Example:

In the file_compressor/ directory, you might create a Python file, such as compress.py, which contains the core functionality of your package, like compressing files into a .zip format.

Here’s an example implementation of compress.py:

import zipfile
import os

def compress_file(input_file, output_file):
    """Compress a single file into a zip archive."""
    with zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
        zipf.write(input_file, os.path.basename(input_file))

    print(f"File {input_file} compressed to {output_file}.")
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the setup.py File

The setup.py file contains important metadata for your Python package, such as its name, version, and description. Here is an example setup.py for file_compressor:

from setuptools import setup, find_packages

setup(
    name='file_compressor',              # Name of your package
    version='0.1.0',                     # Initial version
    packages=find_packages(),            # Find all Python packages
    description='A Python package for compressing files into .zip format',
    long_description=open('README.md').read(),
    long_description_content_type='text/markdown',
    author='Your Name',
    author_email='your-email@example.com',
    url='https://github.com/your-username/file_compressor',  # Link to GitHub repository
    classifiers=[
        'Programming Language :: Python :: 3',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
    ],
    install_requires=[],                 # Add any dependencies here (if needed)
    python_requires='>=3.6',             # Specify the minimum Python version
)
Enter fullscreen mode Exit fullscreen mode
  • name: The name of your package (e.g., file_compressor).
  • version: The current version of your package (start with 0.1.0 for the first release).
  • description: A short description of what your package does.
  • long_description: A detailed description (this can be fetched from your README.md file).
  • author: Your name or organization.
  • author_email: Your email address.
  • url: The URL to your package's homepage (usually your GitHub repository).

Step 4: Create a README.md

A README.md file is essential to explain the purpose of your package and how to use it. Here's a simple example:

# File Compressor

A Python package that compresses files into `.zip` format.

## Installation

Enter fullscreen mode Exit fullscreen mode


bash
pip install file-compressor


## Usage

Enter fullscreen mode Exit fullscreen mode


python
from file_compressor import compress_file

compress_file('path/to/your/file.txt', 'path/to/output/file.zip')

Enter fullscreen mode Exit fullscreen mode

Step 5: Build the Package

Now it’s time to build the package. In your project directory (where setup.py is located), run the following commands:

python setup.py sdist bdist_wheel
Enter fullscreen mode Exit fullscreen mode

This command creates distribution archives, which include:

  • sdist: The source distribution, a .tar.gz file.
  • bdist_wheel: The wheel distribution, a .whl file.

These files will be stored in a dist/ directory inside your project folder.


Step 6: Create a PyPi API Token

To securely upload your package to PyPi, you need to create an API token. Here’s how:

  1. Log in to PyPi: Go to https://pypi.org/ and log in.
  2. Go to Account Settings: Click your username in the top-right corner and select "Account settings".
  3. Create an API Token:
    • Scroll down to the API tokens section.
    • Click "Add API token".
    • Provide a name for the token (e.g., "file_compressor upload").
    • Click "Add token".
  4. Save the API token: Make sure to copy and securely store the token. You’ll only see it once.

Image description


Step 7: Upload to PyPi

Once the package is built, you can upload it using twine. Run the following command to upload the distribution files to PyPi:

twine upload dist/* -u __token__ -p <your-pypi-api-token>
Enter fullscreen mode Exit fullscreen mode

Replace <your-pypi-api-token> with the actual token you generated in the previous step.

This will securely upload your package to PyPi. If the upload is successful, you'll see a confirmation message.

Image description


Step 8: Verify Your Package on PyPi

After uploading, visit https://pypi.org/project/file-compressor/ to verify that your package is live on PyPi. You should see the version, description, and files listed.


Step 9: Install and Test Your Package

To ensure your package is working correctly, try installing it in a new Python environment:

pip install file-compressor
Enter fullscreen mode Exit fullscreen mode

Once installed, test it in a Python script:

from file_compressor import compress_file

compress_file('path/to/your/file.txt', 'path/to/output/file.zip')
Enter fullscreen mode Exit fullscreen mode

If the package works as expected, congratulations! Your package is ready for others to use.


Step 10: Updating Your Package

In the future, if you make any updates to your package, follow these steps:

  1. Modify your package (e.g., add new features or fix bugs).
  2. Update the version number in setup.py (e.g., from 0.1.0 to 0.2.0).
  3. Repeat the build and upload steps to publish the new version.

Conclusion

In this guide, we've gone over the complete process of creating a Python package, specifically the file_compressor package, from scratch. You learned how to:

  1. Set up the package structure.
  2. Write the setup.py and README.md files.
  3. Build and upload your package to PyPi.
  4. Use an API token for secure uploads.

With this knowledge, you can now share your Python packages with the world via PyPi! If you want to explore more about package creation, check out the official PyPi documentation.

Top comments (0)