0

The following simple import fails with error. The python file child.py throws error when it imports a file from the parent dir. I can make it work by adding the parent path in sys.path.append() and importing the file. But I prefer relative import. What is the reason for import error.

(venv) cs@comp-MBP child % ls ../              
__init__.py     child           parent.py

(venv) cs@comp-MBP child % ls
child.py
(venv) cs@comp-MBP child % python child.py 

Traceback (most recent call last):
  File "....some_path/test/child/child.py", line 1, in <module>
    from ..parent import test
ImportError: attempted relative import with no known parent package

Python file contents,

(venv) cs@comp-MBP child % cat ../parent.py 
def test():
    print("calling test function")

(venv) cs@comp-MBP child % 
(venv) cs@comp-MBP % cat child.py 
from ..parent import test
test()
(venv) cs@comp-MBP % 
user2622678
  • 393
  • 1
  • 7
  • 17
  • Do you have an `__init__.py` file in the parent package? Actually, you may need one in the child referring up to the parent. – OneMadGypsy Mar 19 '23 at 05:35
  • Relative imports require that the modules be part of packages; see [this answer](https://stackoverflow.com/a/28154841/), specifically point 3. – metatoaster Mar 19 '23 at 05:40

0 Answers0