Home > Back-end >  What is the right way to do such import
What is the right way to do such import

Time:05-12

So this is my current folder structure

└── Main folder/
    ├── subfolder/
    │   ├── subfolder_function.py
    │   └── subfolder_function2.py
    └── main.py

screenshot

and these are the contents of each file

subfolder_function2.py

def subfolder_function2():
    print("Hey I'm subfolder_function2.py")

subfolder_function.py

from subfolder_function2 import subfolder_function2

def my_function_from_subfolderfunc2():
    subfolder_function2()

main.py

from subfolder.subfolder_function import my_function_from_subfolderfunc2

if __name__ == '__main__':
    print(my_function_from_subfolderfunc2()))

Why do I keep getting this error:

Traceback (most recent call last):
  File "C:\R24\Main folder\main.py", line 1, in <module>
    from subfolder.subfolder_function import my_function_from_subfolderfunc2
  File "C:\R24\Main folder\subfolder_function.py", line 1, in <module>
    from subfolder_function2 import subfolder_function2
ModuleNotFoundError: No module named 'subfolder_function2'

What is the right way to access the function from subfolder_function2.py?

CodePudding user response:

You need to use a relative import in subfolder_function.py to specify you want the import to be from the same directory. See the docs for more information on relative imports

subfolder_function.py

from .subfolder_function2 import subfolder_function2

...
  • Related