1

I have a folder structure as below and I want to import a class from Util1.py into Impl1.py but cannot figure out how to write the Import function. I have seen the mention of PYTHONPATH but cannot completely figure out how to write the details around it. Any help is appreciated

Root folder
 |---Util
     |---Src
         |--Util1.py
         |--Util2.py
 |---Impl1
     |---Src
         |--Impl1.py
         |--Impl2.py

Some information - I am using Python3.4. Please let me know what other information I can provide to help assist you guys help answer my question

2 Answers2

1

The proper way to handle this is to structure your project into packages, then use relative imports. (There are a ton of questions on here about how to do this, for example: [1], [2].

The kludge method that may be necessary if you can't restructure your code is to dynamically add the directory containing your "other" code to your PATH.

For example, assuming you're inside Impl1.py and want to call the foo function inside Util1.py, you could do:

# Get parent of parent
import os, sys
pp = os.path.realpath(__file__)
for _ in range(3): pp = os.path.dirname(pp)
# Add np to path
sys.path.append(os.path.join(pp, 'util', 'src'))

# Import file
import Util1

# Call function
Util1.foo()
Community
  • 1
  • 1
jedwards
  • 29,432
  • 3
  • 65
  • 92
  • When you say "pp = os.path.realpath(__file__)". The __file__ is the complete path to the Util1.py like /home//workspace/Root/Utils/src/Util1.py – TheSilentProwler Mar 17 '15 at 06:37
  • Okay, so then you're inside Util1.py trying to get somewhere else -- update the arguments to `join`, and the `import` appropriately. `pp` is initialized to that path , then the next line goes 3 directories up (Src, Util, Root) – jedwards Mar 17 '15 at 06:38
0

you can use relative import e.g

For example to import a class 'foo' from Util1.py into Impl1 you can write this in Impl1.py

from ../../Util/Src/Util1 import foo

Further reading : https://stackoverflow.com/a/12173406/2073920

Community
  • 1
  • 1
Abdul Rauf
  • 5,798
  • 5
  • 50
  • 70