Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share code between python projects?

Let's say that I have two projects with the following structure:

/project1
/project2

Now I have developed a function/class that could be useful to the both projects. I would like to put it somewhere out of the project1/project2 directories and to maintain it as a separate project. So I probably need structure like this:

/project1
/project2
/shared

If I put my helper functions/classes in the project that will be in the shared folder, how to use them from project1/project2?

At the moment my option is to use sys.path.append('/shared') in project1/project2 and after it to do import(s) from shared folder.

Is there some more pythonic way to do the same?

like image 874
user3225309 Avatar asked Jan 18 '26 05:01

user3225309


1 Answers

You can import /shared using parent module, as long as the parent module is in PYTHONPATH. If your project would look like:

toplevel_package/
├── __init__.py
├── main.py
└── project1
    ├── __init__.py
    └── foo.py
└── project2
    ├── __init__.py
    └── bar.py
└── shared
    ├── __init__.py
    └── save_files.py

Then imports would look like:

from toplevel_package.shared import save_files

This works as long as toplevel_package is in your PYTHONPATH. Either:

  1. Only launch toplevel_package scripts (which can then call subpackages)
  2. Move toplevel_package module to any folder listed in PYTHONPATH
  3. Add toplevel_package to PYTHONPATH

More info can be found in import from parent.

You could also simply use import using full path, which is not as pythonic in my opinion but works well in some situations (in the end, .

like image 75
JuhaniTakkunen Avatar answered Jan 20 '26 22:01

JuhaniTakkunen



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!