简体   繁体   中英

What is the right way to do such import

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?

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

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM