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?

2
  • I suggest to read the question. I do not want to make any code changes. Commented May 31, 2021 at 9:33
  • Does this answer your question? Relative imports in Python 3 Commented May 31, 2021 at 9:35

1 Answer 1

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...)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this suggestion, but this does not seem to work. I get an error /usr/local/opt/[email protected]/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')
Be sure to clear any PYTHONPATH changes you may have made. Also, -m tut_bs.test_module, no .py extension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.