0

I have the following file structure

enter image description here

In main.py I am attempting to import a class which is located in property.py.

When I try putting the following at the top of main.py

from B.C.property import Property

I get:

ModuleNotFoundError: No module named 'B'

If I instead try

from ..B.C.property import Property

I get

ImportError: attempted relative import with no known parent package

Any help appreciated!

deceze
  • 510,633
  • 85
  • 743
  • 889
Tah
  • 41
  • 1
  • 7
  • How are you *running* the program? It’s just not run from the right working directory/not set up with the correct environment variables to find that other module. – deceze Aug 04 '23 at 06:33
  • I am just using VSCode default behaviour to run main.py. So, my local python.exe is just run with the absolute path of main.py, i.e. "C:/Users/../Python39/python.exe C:/Users/.../A/main.py" – Tah Aug 04 '23 at 06:38
  • 1
    I don’t use VSC, but if you can configure the runner, configure it to set the working directory to the directory *above* both A and B. Alternatively, set the `PYTHONPATH` environment variable to that directory. – deceze Aug 04 '23 at 06:39
  • What folder is your workspace? Is it the folder where A and B are located? Please show the complete folder structure. – JialeDu Aug 04 '23 at 06:51
  • i believe the problem is because main.py is in folder A which also has `__init__.py` making it a package. Move main.py to the base directory, and make A and B subfolders of that directory. See also https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time/14132912#14132912 – nigh_anxiety Aug 04 '23 at 06:54
  • You should package your project and use an editable install for development. – juanpa.arrivillaga Aug 07 '23 at 05:57
  • https://packaging.python.org/en/latest/tutorials/packaging-projects/ – juanpa.arrivillaga Aug 07 '23 at 06:01

1 Answers1

0

You can add the correct path to PYTHONPATH using sys.path.append(), or add PYTHONPATH using .env file or configuration in launch.json.

JialeDu
  • 6,021
  • 2
  • 5
  • 24