I am using Python 3.10.4 and I have the following setup:
__init__.py
a.py
child
__init__.py
b.py
a.py:
def add(a,b):
return a+b
b.py:
from ..a import add
print(add(2,3))
init.py files are empty.
My issue is that in this setup running python child/b.py from the top level directory here always results in "ImportError: attempted relative import with no known parent package"
I have tried various suggestions from Relative imports in Python 3 including trying to append the path using the following but that didn't help :
import sys
import os
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))
The only way I have been able to make this work is by using an absolute import and exporting the working directory path to PYTHONPATH using export PYTHONPATH=.
How do I make relative imports work?
Thanks!