-
Structure Your Package Properly
Create a directory for your package with the necessary files. Here's a minimal example of how your directory structure should look:
mypackage/
setup.py
mypackage/
__init__.py
module1.py
module2.py
mypackage/: The root directory of your package.
setup.py: A script for setuptools to build and install your package.
mypackage/: A subdirectory containing your package code.
__init__.py: An empty file indicating that this directory is a Python package.
module1.py, module2.py: Your Python modules.
-
Create a setup.py File
The setup.py file tells setuptools how to build your package. Here's a simple example:
from setuptools import setup, find_packages
setup(
name='mypackage',
version='0.1',
packages=find_packages(),
)
This script uses setuptools to find your packages and prepares them for installation.
-
Install the Package in Editable Mode
Use pip to install your package in editable mode. Editable mode means that the package is linked to the source directory, and changes to the code are immediately available without reinstalling.
Open a terminal, navigate to the root directory of your package (where setup.py is located), and run:
pip install -e .
The -e or --editable flag tells pip to install the package in editable mode. The . specifies the current directory.
-
Verify Installation
You can verify that your package is installed by running:
pip list
Your package mypackage should appear in the list. It will be indicated as editable.
-
Use Your Package in Your Projects
Now, you can import your package in your Python scripts:
import mypackage
-
Modify Your Package Without Reinstallation
Since the package is installed in editable mode, any changes you make to the source code in your package directory are immediately available the next time you import the package or reload the module in an interactive session.
For example, if you add a new function to module1.py, you can use it without reinstalling:
from mypackage.module1 import new_function
By following these steps, you have a local Python package that's easy to maintain and develop. You can modify the code as you like, and your projects using the package will always access the latest version without additional installation steps.
You can create and install a local package in editable mode using pip. First, structure your package properly with a setup.py file, then install it with pip install -e /path/to/your/package. This way, any changes you make to the package code are immediately available without needing to reinstall.