-1

Okay, pictured are the two MWE's and their failure messages.

In words, I can't naturally import, from the same subdirectory, into a module that I want to run as main for testing purposes. That's the first screenshot.

The next screenshot shows that I cannot naturally import, from the project root, into a subdirectory module that I am similarly running as main for testing purposes.

Visuals:

Import in project subdir fails when running as main, and importing from subdir


Import from project subdir fails when running as main, and importing from project root

What I don't want to do is hack my way through like I've been doing in all my projects with lines such as:

if __name__ == '__main__:
    import sys
    sys.append('..')

This is inelegant because it doesn't withstand changing the folder structure.

I've also tried putting in blank __init__.py's into the subdirs and also tried putting in those the lines such as:

from .e import E

Nothing easy seems to work. It's really a bummer when I can't handle basic file structures when importing things.

So what is the general fix that solves both of these issues for good and forever?


Text Code:

<proj root>/d.py:

 class D:
     pass

<proj root>/root.py:

from b.a import A

print("import from project root main")

<proj root>/b/a.py:

from b.c import C

class A(C):
    pass

if __name__ == '__main__':
    print('import from project subdir')

<proj root>/b/c.py:

class C:
    pass 

<proj root>/b/e.py:

from d import D

class E(D):
    pass

if __name__ == '__main__':
    print("e can't import something from root")

First set entry point to a.py and for the other error set entry point to e.py.

Thank you!

MathCrackExchange
  • 595
  • 1
  • 6
  • 25

1 Answers1

0

For the first error, you create an __init__.py in the subdir b with the contents:

from .c import *

The same does not work for the root directory however. But the most succinct way I've found, without having to do a sys.path.append() is to open up your project properties, and add precisely .. to the Python Path:

In WingWare:

Wingware Project Properties Dialog

And that solves the second issue. There is a warning when you add simply .. that you should use absolute paths, but I'm okay with that.

If you work without an IDE simply modify the PYTHONPATH environment variable.

Happy Coding!

MathCrackExchange
  • 595
  • 1
  • 6
  • 25