0

Here is my directory structure,

dir1
    dir1f.py

dir2
    dir2f.py
    __init__.py

dir2f.py has a class class dir2c that I want to import inside dir1f.py so in dir1f.py I called

from ..dir2.dir2f import dir2c

but I get this error

SystemError: Parent module '' not loaded, cannot perform relative import

What is wrong?

yooth
  • 361
  • 1
  • 3
  • 4
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]. – T-Heron Mar 04 '17 at 02:05
  • Possible duplicate of [Relative imports in Python 3](http://stackoverflow.com/questions/16981921/relative-imports-in-python-3) – Pike D. Mar 04 '17 at 04:42

1 Answers1

0

As T-Heron notes, it's hard to tell exactly what you're trying to do here, but if I had to hazard a guess I'd say you're running dir1f.py as a script (ala python dir1/dir1f.py or python dir1f.py from the dir1 directory) which means you shouldn't use relative imports. Try:

from dir2.dir2f import dir2c

Update: If executing with python dir1f.py, there are a few ways to go:

  1. try python dir1/dir1f.py from the top-level directory first; or
  2. move dir2 into dir1 and run python dir1f.py from dir1; or
  3. read up on PYTHONPATH (environment variable)

Also: have a read of PEP8, especially the imports section:

"Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path)."

-- http://pep8.org/#imports

Possibly related, with quite a bit more detail: Relative imports in Python 3

Community
  • 1
  • 1
glennji
  • 349
  • 1
  • 4
  • I'm executing python dir1f.py from dir1 so executing from dir2.dir2f import dir2c produces error ImportError: No module named 'dir2' – yooth Mar 04 '17 at 02:32
  • Updated my answer -- you should be able to `from dir2.dir2f import dir2c` if `dir2/` is inside `dir1/` instead of being at the same level. – glennji Mar 04 '17 at 03:29