Importing from folders with the same name gives ImportError

Given the following project structure:

test/
 data/
   __init__.py
 a/
   data/
     __init__.py
   main.py
 __init__.py

In test/data/__init__.py

from pathlib import Path
DATA_DIR = Path(__file__).parent

In main.py

from data import DATA_DIR

if __name__ == "__main__":
    print(DATA_DIR)

When running from the terminal, it works fine. When running from PyCharm, it gives the following error:

Traceback (most recent call last):
File "/Users/<USER>/code/test/a/main.py", line 1, in <module>
from data import DATA_DIR
ImportError: cannot import name 'DATA_DIR' from 'data' 
(/Users/<USER>/code/test/a/data/__init__.py)

Has anyone found a way to get around this?

0
1 comment
PyCharm can modify your PYTHONPATH based on which directories are marked as sources (https://www.jetbrains.com/help/pycharm/project-structure-dialog.html#e4286cf4)

Try unmarking the `test/a` directory and mark `test` dir instead.
0

Please sign in to leave a comment.