0

i have a third party package which looks like this:

packagename
├── subfolder1
|   ├── Someclass11.py
|   ├── ...
|   └── __init__.py <- EMPTY
├── subfolder2
|   ├── Someclass21.py
|   ├── ...
|   └── __init__.py <- EMPTY
├── Someclass1.py
├── Someclass2.py
├── ...
└── __init__.py

packagename/__init__.py looks like this:

from packagename.subfolder1.Someclass11 import Someclass11
from packagename.subfolder2.Someclass21 import Someclass21
from packagename.Someclass1 import Someclass1
from packagename.Someclass2 import Someclass2

My own Project has this structure:

projectname
├── thirdParty
|   ├── packagename
|   └── ...
├── subfolder2
|   └── ...
├── ...
└── main.py

I want to include the Classes from packagename in my main.py (and in other classes/functions). This works if I change the packagename/__init__.py to:

from projectname.thirdParty.packagename.subfolder1.Someclass11 import Someclass11
from projectname.thirdParty.packagename.subfolder2.Someclass21 import Someclass21
from projectname.thirdParty.packagename.Someclass1 import Someclass1
from projectname.thirdParty.packagename.Someclass2 import Someclass2

Are there solutions to import packagename without editing packagename/__init__.py and having other functions import it from different locations?

Jonas
  • 1,838
  • 4
  • 19
  • 35

1 Answers1

0

You must have the thirdParty folder in the PYTHONPATH.

On Linux/MacOS:

$ export PYTHONPATH=<path_to_projectname>/thirdParty

On windows: see this answer.

An alternative to set a new pythonpath, is to add something like the following in the main.py, before importing the thirdParty package:

import sys
import os
base_dir = os.path.dirname((os.path.abspath(__file__)))
thirdParty_dir = os.path.join(base_dir, 'thirdParty')
sys.path.insert(0, thirdParty_dir)

despite this snippet can be a little version dependent (I tested it in python 3.5).

Riccardo Petraglia
  • 1,943
  • 1
  • 13
  • 25