Issue
I have some code that is reused in other projects. I would like to separate this code into a separate project, update and improve it separately, but at the same time share it in other projects. What are the best practices currently used to solve this problem? I see that many people are asking this question, but there are no specific good answers. For example, many people suggest using the setup file. But then it is not clear how to automatically update old packages in other projects if I make new improvements to the code that I plan to use in other projects.
The project structure looks something like this:
dir CommonProject
- utilities.py
dir Project1
- main.py #import utilities
dir Project2
- main.py #import utilities
I want to use functions from utilities.ru in main.py project1 and main.py project2
Solution
That's what packaging is used for! You can make your project CommonProject
a package, and then install it locally to make it available to your other programs.
Make CommonProject
a package
In order to make your project a package, it needs to follow a certain structure:
mypackage/
├─ __init__.py
├─ utilities.py
You need a __init__.py
file, that you can leave empty, to make your project a proper Python package.
Add a setup.py
file
At the root of your common project's directory, you need to add a file named setup.py
. This file will be recognized by pip
, and will contain all the required information about your package.
# setup.py
from distutils.core import setup
setup(
name='mypackage', # Required
version='1.0.0', # Required
description='<description>',
author='<your name>',
author_email='<your email>',
packages=['mypackage'], # Required
)
Most fields are not required, but can be useful if you intend to share your project someday.
Install the package
Once you have a setup.py
file, you can tell pip to install it to your environment, using the command:
pip install -e <path to your package>
The -e
option means that your package will be in editable mode, thus you will be able to make modifications to the source code of the package without having to reinstall it each time.
Use the package in your other projects
If you properly installed the package into your environment, you will be able to use it in your other programs by simply importing it:
# Project1/main.py
from mypackage import utilies
...
This is a basic example of how to make a proper Python package, and how to make it available to your other projects locally.
Answered By - Ebig
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.