0

My structure looks something like this:

project/->
   app.py
   checker/->
      exc.py
      anc.py

My files are simple:

# app.py
from checker.exc import ExampleClass

# checker/exc.py:
from anc import AnotherClass

class ExampleClass(AnotherClass):
    print('Example')

# checker/anc.py:
class AnotherClass:
    print('AAAA')

When I run exc.py inside checker folder everything works ok, same when I run app.py with module from package checker everything works perfect.

But when I run app.py which uses class from checker.exc, and exc need anc. I have an error ModuleNotFoundError: No module named anc

eudaimonia
  • 1,406
  • 1
  • 15
  • 28
  • The [difference between relative and absolute imports](https://realpython.com/absolute-vs-relative-python-imports/) might help you there. As you're working on the app.py level, there is no anc.py file, but a checker.anc.py file. You should import anc.py on the exc.py as a relative import, which will break other ways of using it. [See also this answer](https://stackoverflow.com/a/14132912/3026320). – berna1111 Jun 23 '19 at 23:33

2 Answers2

2

Realise this is a duct tape solution.

Change exc.py to:

try:
    from anc import AnotherClass
    print('abs import')
except ModuleNotFoundError:
    from .anc import AnotherClass
    print('rel import')

class ExampleClass(AnotherClass):
    print('Example')

That way you can use absolute import when debugging, for instance, but rely on relative import when importing it running app.py on it's own.

The order in which you attempt to import them should reflect the expected use, with the one most expected to be used being attempted first. The error is the same if you switch the attempts.

berna1111
  • 1,811
  • 1
  • 18
  • 23
1

Since the code is being run from the project folder, in order for exc.py to find anc.py you need to change exc.py to the following:

from .anc import AnotherClass

class ExampleClass(AnotherClass):
    print('Example')

As berna1111's comment suggests, this may cause problems when running exc.py directly.

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35