0

My files are:

main.py
dir/func.py
dir/mod.py

My main.py has from dir import func
My func.py has import mod

When I run main.py it gives me:
ModuleNotFoundError: No module named 'mod'

I am using Python 3.10, so what I have read, I do not need the __init__.py file.

Now, it does work if I put from dir import mod in func.py. Is there any way to not have to do that. Is there a better, more elegant way? Because I might have to be calling func.py from different directories in the future.

  • try from . import mod or from .mod import mod (not sure exactly) – Simon Hawe Jan 12 '22 at 15:03
  • @SimonHawe `from . import mod` works. Thank you. But ideally I am looking for something more elegant. Because in my real project, the dir folder has many different modules. With them all importing each other, this would mean I would have import all in all of them. Is no other solution exists, I would have to use this. – Yashoraj Agarwal Jan 12 '22 at 15:32

1 Answers1

1

You can create a new package directory

from foldername.filename import func

make sure to include an empty _init_.py file in the directory. This file tells Python to treat the directory as a package

naif_d
  • 66
  • 5
  • I added \_\_init_\_.py in the dir folder. It is giving me the same error. And what would `from foldername.filename import func` correspond in my case? Is it just `from dir import mod` – Yashoraj Agarwal Jan 12 '22 at 15:25
  • foldername is the dir name in your case and the filename is the func,py without .py – naif_d Jan 13 '22 at 11:59