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?
-
Why do not you create a libraries?eyllanesc– eyllanesc2018年02月23日 19:26:42 +00:00Commented Feb 23, 2018 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– user32253092018年02月24日 14:16:55 +00:00Commented Feb 24, 2018 at 14:16
1 Answer 1
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:
- Only launch toplevel_package scripts (which can then call subpackages)
- Move toplevel_package module to any folder listed in PYTHONPATH
- 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, .