Thursday, 20 April 2023

How to create Python package locally and use in different project?

To create a Python package locally and use it in different projects, you can follow these steps:

  1. Create a new directory for your package. For example, you can name it mypackage.
  2. Inside the mypackage directory, create a file called __init__.py. This file tells Python that this directory is a package.
  3. Create your Python module(s) in the mypackage directory. For example, you can create a module called mymodule.py.
  4. Inside your module, define your classes and functions.
  5. Create a setup.py file in the mypackage directory. This file contains the package's metadata and tells Python how to install the package. Here is an example of what your setup.py file could look like:
from setuptools import setup, find_packages

setup(
    name='mypackage',
    version='0.1',
    packages=find_packages(),
    install_requires=[
        # list any dependencies your package has
    ],
)

6. Install your package locally by running python setup.py install.

7. Now you can use your package in any other Python project by importing it like this:

import mypackage
from mypackage import mymodule
That's it! Your package is now ready to be used in any Python project. You can continue to add new modules or update your existing modules in your mypackage directory, and then reinstall your package using python setup.py install to use the updated code in other projects.