user3225309
user3225309

Reputation: 1373

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?

Upvotes: 15

Views: 8498

Answers (1)

JuhaniTakkunen
JuhaniTakkunen

Reputation: 176

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, .

Upvotes: 8

Related Questions