3

Below is an example of my project.

When running foo.py I get:

ModuleNotFoundError: No module named 'foo.bar'; 'foo' is not a package

Renaming the foo/ directory or the foo.py file solves the problem, but I'd love to know if there is another way and why this is happening?

project/
        |
        foo/
        |  __init__.py
        |  foo.py
        |  bar.py
        |
        setup.py

In foo.py

import foo.bar

    if __name__=='__main__':
       pass
informatik01
  • 16,038
  • 10
  • 74
  • 104
Ron
  • 197
  • 1
  • 10
  • The answer depends on what you mean by "when run foo.py" You're going to need to clarify that. What did you do when you ran foo.py? – Mike Apr 12 '21 at 19:14

1 Answers1

7

The issue is likely how you're running foo.py as a script. If you run python foo.py from inside the project/foo directory, Python will assume that foo.py is a module at the global level, and that will prevent the foo/ folder from being seen as a global package (even if project/ is in the module search path). It would expect to import bar.py as bar at the top level too, rather than as a module within a foo package.

You can probably work around this issue by changing how you run foo.py. Instead of python foo.py, try python -m foo.foo (from the project/ folder, if necessary).

It may also be possible to work around some of the issues by setting a __package__ value in your modules (see here for another answer explaining __package__ and providing some useful links). That might only fix explicit relative imports between modules in the package though (so you could change import foo.bar to from . import bar and it would work), but I'm not sure if it can restore the foo package to its proper place in the global namespace (so other code outside the package might still break).

Blckknght
  • 100,903
  • 11
  • 120
  • 169