Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading