Introduction
As software engineers, we often find ourselves reusing code across different modules and projects. But let's face it, this repetition creates a challenge: when we need to adjust or fix that code, we have to make the same changes in multiple places. For those of us who value efficiency and automation, the solution is clear - create a separate package that can be installed and used across our projects.
However, when dealing with confidential code, we can't simply publish our package on public repositories like PyPI. Instead, we need to deploy it to a private repository such as GitHub or GitLab. This approach allows us to maintain security while still benefiting from the convenience of a reusable package.
In this tutorial, we’ll guide you through the process of:
- Creating a Python package
- Deploying the package to a private repository (GitHub)
- Installing the package in a virtual environment (venv)
By following these steps, you'll be able to reduce code duplication and simplify maintenance of shared code across your projects.
Note: DRY doesn't just stand for "Don't Repeat Yourself" - it's also a lifestyle choice.
1. Setting Up Your Project Structure
First, let's set up a basic project structure for our Python package:
my-package/ ├── my_package/ │ ├── __init__.py │ └── module1.py ├── setup.py ├── build.pipeline.yml ├── requirements.txt ├── .gitignore ├── README.md ├── MANIFEST.in └── LICENSE
Let's break down the anatomy of our private Python package. Each file and directory plays a crucial role in making our package functional and installable:
- my-package/: This is the root directory of our project. It's like a house that contains all the rooms (files) we need.
-
my_package/: This subdirectory is where the actual Python code lives. It's named the same as our package for clarity.
- __init__.py: This file makes Python treat the directory as a package. It can be empty or can execute the initialization code for the package.
- module1.py: This is where we put our main code. You can have multiple module files depending on your package's complexity.
- setup.py: Think of this as the instruction manual for our package. It contains metadata about our package (like its name and version) and lists its dependencies. This file is essential for making our package installable via pip.
- requirements.txt: This file lists all the external Python packages our project depends on. It's like a shopping list for pip, telling it exactly what to install to make our package work.
- README.md: This is the welcome mat of our project. It's usually the first thing people see when they visit our GitHub repository, so we use it to explain what our package does, how to install it, and how to use it.
- .gitignore: This file tells Git which files or directories to ignore. It's handy for keeping compiled code, temporary files, or sensitive information out of version control.
- LICENSE: This file specifies how others can use, modify, or distribute our package. It's crucial for open-source projects and helps protect our work.
- MANIFEST.in: This file is used to include non-Python files in our package distribution. If we have data files, documentation, or other resources that need to be included, we list them here.
- build.pipeline.yml: This file defines our Continuous Integration/Continuous Deployment (CI/CD) pipeline. It automates tasks like running tests and building the package when we push changes to our GitHub repository.
2. Creating the Package Code
Let's create a simple module within our package. In my_package/module1.py:
my-package/ ├── my_package/ │ ├── __init__.py │ └── module1.py ├── setup.py ├── build.pipeline.yml ├── requirements.txt ├── .gitignore ├── README.md ├── MANIFEST.in └── LICENSE
In my_package/__init__.py, we'll import our module:
class Hello: def __init__(self, name): self.name = name def greet(self): return f"Hello, {self.name}!"
3. Creating setup.py
The setup.py file is crucial for packaging our project. Here's a basic example:
from .module1 import Hello
4. Creating requirements.txt
In our requirements.txt file, we include the necessary dependencies for building and distributing our package:
from setuptools import setup, find_packages with open('requirements.txt') as f: requirements = f.read().splitlines() setup( name="my_package", version="0.1", include_package_data=True, python_requires='>=3.8', packages=find_packages(), setup_requires=['setuptools-git-versioning'], install_requires=requirements, author="Abdellah HALLOU", author_email="abdeallahhallou33@gmail.com", description="A short description of your package", long_description=open('README.md').read(), long_description_content_type="text/markdown", classifiers=[ "Programming Language :: Python :: 3.8", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], version_config={ "dirty_template": "{tag}", } )
5. Building and Installing Your Package
Install the requirements. To keep things simple, we will use the Python virtual environment.
setuptools==69.2.0 wheel twine
To build our package:
python -m venv env source env/bin/activate # for linux and mac ./env/Scripts/activate # for windows pip install -r requirements.txt
To install our package locally for testing:
python setup.py sdist bdist_wheel
You can commit your work and ignore the folders using .gitignore file:
https://github.com/github/gitignore/blob/main/Python.gitignore
6. Publishing the Package on GitHub with a tag
To publish the package, first, create a build.pipeline.yml file at the root of the project my-package/ and commit it. The deployment will be done with twine, the library that we installed before:
my-package/ ├── my_package/ │ ├── __init__.py │ └── module1.py ├── setup.py ├── build.pipeline.yml ├── requirements.txt ├── .gitignore ├── README.md ├── MANIFEST.in └── LICENSE
If you need to include non-Python files with your module installation, you can use a MANIFEST.in file. This file specifies which additional files should be included in your package distribution.
class Hello: def __init__(self, name): self.name = name def greet(self): return f"Hello, {self.name}!"
Then upload the package:
from .module1 import Hello
7. Install the Package
Create an access token:
- Go to Settings > Developer Settings > Personal access tokens (classic) > Generate new token.
- Ensure you check the write:packages scope to grant the necessary permissions.
Once you have your token, keep it secure, as you'll need it to install your package.
On your machine, you can install your private package using the following template:
from setuptools import setup, find_packages with open('requirements.txt') as f: requirements = f.read().splitlines() setup( name="my_package", version="0.1", include_package_data=True, python_requires='>=3.8', packages=find_packages(), setup_requires=['setuptools-git-versioning'], install_requires=requirements, author="Abdellah HALLOU", author_email="abdeallahhallou33@gmail.com", description="A short description of your package", long_description=open('README.md').read(), long_description_content_type="text/markdown", classifiers=[ "Programming Language :: Python :: 3.8", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], version_config={ "dirty_template": "{tag}", } )
Conclusion
Well done, you know now how to create and deploy your own private packages with Python on GitHub.
Github repository link : https://github.com/ABDELLAH-Hallou/Private-Python-Package-Deployment
The above is the detailed content of Create and Release a Private Python Package on GitHub. For more information, please follow other related articles on the PHP Chinese website!

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
