0

(I appreciate there are many similar questions on StackOverflow already, but none seemed to help me.)

I have the following structure:

code/
  foo/
    __init__.py
    foo.py
    bar/
      __init__.py
      bar.py

I want to be able to import foo as a package in bar.py without messing with sys.

This is my foo.py:

hello = 'Hello, world!'

This is my bar.py:

import foo

print(foo.hello)

But if I execute python foo/bar/bar.py I get the following error:

ModuleNotFoundError: No module named 'foo'

Of all things, the one that's driving me crazy the most is that if I add the following snippet on top of bar.py:

import pkgutil

search_path = ['.']
all_modules = [x[1] for x in pkgutil.iter_modules(path=search_path)]
print(all_modules)

Then I actually get foo as an available module (still failing), here:

['foo']
ModuleNotFoundError: No module named 'foo'
Edgar Derby
  • 2,543
  • 4
  • 29
  • 48
  • Does this answer your question? [How to Import python package from another directory?](https://stackoverflow.com/questions/61234609/how-to-import-python-package-from-another-directory) – RMPR May 04 '20 at 11:52
  • Thanks for the comment. It does not, they use PYTHONPATH (sys) which I don't want to, plus that thread's OP is trying to import a sibling module, whilst I want to import the current package. – Edgar Derby May 04 '20 at 11:57
  • Look at the last approach, it doesn't use `sys` and it's pretty much the same principle. – RMPR May 04 '20 at 11:59

0 Answers0