Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to reuse my own function in new projects? [closed]

What is the best way to easily add functions I make to new projects? I have made a bunch of python functions that I created myself that I use frequently for my projects, but I lose track of where I put them all and their versions become desynced when I change them

Should I just add all these functions to pypi? That seems time consuming, especially since a lot of these are pretty small.

I could also save the function as .py files and add them to the directories I make new projects on and import with a simple import. But the problem with this is if I change something about the original I would need to track down every instance of my function file and replace them with the new file.

I could also use absolute path imports, which I've looked at briefly. They seem pretty annoying for what they are, but that's maybe less of an annoyance than tracking down every copy of the file every time I change it. The other big problem with that is I do a lot of cloud computing, which would break my code every time I transition from running it locally to on the cloud, and force me to copy the code anyway.

Has anyone here run into a similar problem? Have you developed a nice solution to it? Is there an option I haven't thought of? All suggestions welcome!

like image 643
SSC Fan Avatar asked Feb 04 '26 22:02

SSC Fan


1 Answers

Here's basic example to create a local package.

Folder Structure

root/
├─ mypackage/
│  ├─ __init__.py
│  ├─ func.py
setup.py

__init__.py

from .func import foo

setup.py

from distutils.core import setup


setup(name="mypackage",
      version='1.0',
      description='',
      packages=["mypackage"],
     )

func.py

def foo():
    print("foo")
    return

Steps

Build and Install

Run following in terminal. Activate your project environment beforehand.

cd root
python setup.py sdist
pip install ./dist/mypackage-1.0.tar.gz

Usage

Activate your environment first. Then run following in python console:

>>> import mypackage
>>> mypackage.foo()
# foo
like image 74
d.b Avatar answered Feb 06 '26 10:02

d.b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!