0

Even with an __init__.py in the parent directory.

parentDir\
    __init__.py
    targetDir\
        __init__.py
        something.py
    thisDir\
        main.py

In main.py:

import .targetDir.something

This does not work. I tried:

from . import targetDir
from targetDir import something

This doesn't work, either. Are there any Pythonic solutions for doing something as simple as importing a module from a directory in the parent directory?

Coffee Maker
  • 1,543
  • 1
  • 16
  • 29
  • You need `__init__.py` in `thisDir` as well. You should also read [this question](http://stackoverflow.com/questions/11536764/attempted-relative-import-in-non-package-even-with-init-py) and [this question](http://stackoverflow.com/questions/14132789/python-relative-imports-for-the-billionth-time) – BrenBarn Jun 12 '14 at 20:15

2 Answers2

0

I believe you'd need __init__.py in thisDir and then you need to go up a level in the package hierarchy:

from ..  import targetDir

or:

from ..targetDir import something
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

May be this is not a cleanest solution, but you can do something like this:

import sys
import os

topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
                                       os.pardir, os.pardir))
if os.path.exists(os.path.join(topdir, "targetDir", "__init__.py")):
    sys.path.insert(0, topdir)

from targetDir import something

Example:

mkdir -p parentDir/targetDir
mkdir -p parentDir/thisDir
touch parentDir/__init__.py
touch parentDir/targetDir/__init__.py
echo "print 'Im here'" > parentDir/targetDir/something.py

then place the code in parentDir/thisDir/main.py and it should print Im here

Vor
  • 33,215
  • 43
  • 135
  • 193