1

I have a query over modules in Python.

Using VSCode I have the following simple code set up:

Demo/
    Test.py
    z1/
        \_\_init\_\_.py
        Foo.py
        z2/
            \_\_init\_\_.py
            Screen.py

screen.py contains:

class Screen:
SCREEN_SIZE = [800, 600]

and z2/__init__.py

from  z1.z2.Screen import *

and both the following Foo.py and Test.py have:

from z1.z2.Screen import *
print(Screen.SCREEN_SIZE)

why is it when I run Test.py, I get:

[800, 600]

But when I run Foo.py, I get:

File "***\Python\z1\Foo.py", line 1, in <module>
    from z1.z2 import *
ModuleNotFoundError: No module named 'z1'

I can changed the z1.z2 in the __init__.py to just z2, but then Test.py doesn't work. Is there any means to have it work for both files?

Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
  • I believe the issue was how I set up the environment, and that the project directory was not added to PYTHONPATH, which is why the absolute import was not working. – Llosgfynydd Nov 28 '21 at 20:15

2 Answers2

0

I personally do not like Pythons import system. When running Foo.py are you able to import use from z2.Screen import * successfully?

I have (unfortunately) used the following to work for test code as well

try:
    from x.y import z
except ImportError:
    from y import z

But I guess you could use os.path to add root path to Foo.py as well. In Foo.py you could try adding

import sys

sys.path.append('../')
smbfml
  • 46
  • 4
0

It appears you are not using a virtual environment, which causes the files to run sort-of independently.

As is, you are trying to import z1 inside Foo.py, but Foo.py only sees a sub-folder named z2. Changing the import statement in Foo.py to from z2.Screen import * fixes the issue for the time being.

If using a virtual environment, then you'd have to use import as if the file is located in the main directory.

As a side-note, this might give some better insight to using _init_.py

Tõnis Piip
  • 482
  • 2
  • 9
  • So if I make the interpreter look in my Demo folder for all the modules, it should then work? Is there not a way to make sure VSCode always treats the project folder as the place to search for packages/modules, otherwise you couldn't use absolute paths anywhere but files in the main project folder – Llosgfynydd Nov 01 '21 at 12:32
  • I was trying to use absolute import from the project folder, which I have fixed by adding to the PYTHONPATH. – Llosgfynydd Nov 28 '21 at 20:16