14

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?

user3225309
  • 1,183
  • 3
  • 15
  • 31
  • Why do not you create a libraries? – eyllanesc Feb 23 '18 at 19:26
  • Let's say that I have a MyModule in shared folder in which is a class MyClass definition: /project1 /project2 /shared/MyModule(MyClass) How to create a subclass of MyClass in Project1/Project2 folders? – user3225309 Feb 24 '18 at 14:16

1 Answers1

8

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

Tai
  • 91
  • 6
  • 2
    Thank you very much for your explanation. I am now using PYTHONPATH and directory structure as you have suggested and everything works well. Thanks – user3225309 Mar 04 '18 at 21:40