1

In python I have a folder with three files

- __init__.py
- module.py
- test_module.py

in which the module module.py is imported inside the file test_module.py as follows:

from . import module

Of course, when I just run test_module.py I get an error

> python test_module.py
Traceback (most recent call last):
  File "test_module.py", line 4, in <module>
    from . import module
ImportError: attempted relative import with no known parent package

But as I set the PYTHONPATH to the absolute path to where I am working in

export PYTHONPATH=`pwd`

I expect the import to work (as I did set the PYTHONPATH). But to my surprise I get the same error!

So can I fix the relative import error without any code change?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Alex
  • 41,580
  • 88
  • 260
  • 469
  • I suggest to read the question. I do not want to make any code changes. – Alex May 31 '21 at 09:33
  • Does this answer your question? [Relative imports in Python 3](https://stackoverflow.com/questions/16981921/relative-imports-in-python-3) – mkrieger1 May 31 '21 at 09:35

1 Answers1

2

Since the directory you describe (let's call it thatdirectory) is a package, as marked by an __init__ file, you can "fix" that by cding a directory higher up, then running

python -m thatdirectory.test_module

since running modules with -m fixes up sys.path in a way that makes this particular configuration work.

(In general, any code that messes with sys.path manually, or requires changes to PYTHONPATH to work, is broken in my eyes...)

AKX
  • 152,115
  • 15
  • 115
  • 172
  • Thanks for this suggestion, but this does not seem to work. I get an error `/usr/local/opt/python@3.8/bin/python3.8: Error while finding module specification for 'tut_bs.test_module.py' (ModuleNotFoundError: __path__ attribute not found on 'tut_bs.test_module' while trying to find 'tut_bs.test_module.py')` – Alex May 31 '21 at 09:37
  • 1
    Be sure to clear any `PYTHONPATH` changes you may have made. Also, `-m tut_bs.test_module`, no `.py` extension. – AKX May 31 '21 at 09:37