Lucas Tonon
Lucas Tonon

Reputation: 127

Import from different folder/module in python

I have the following structure of folders

project\
       main.py

       datasets\
                __init__.py
                custom_data.py
       models\
                __init___.py
                model1.py
                model2.py
                func.py

I would like to import func.py inside custom_data. (without using auxiliary libraries)

the main function imports custom_data.py with:

from datasets.custom_dataset import build as build_dataset

And when the code is running custom_dataset it fails to find the module func

ModuleNotFoundError: No module named 'func'

I have already tried anything I saw here in stackoverflow:

from ..models import func from project.models import func

I even tried to copy func.py as a duplicate inside datasets, but it doenst work at all (it does work when I use the func functions inside the custom_data.py, but does not when I call it from the main.py file).

Can anyone help me? Is it because I'm using windows maybe? I know I can find a lot of other questions related to this but none have helped me at all.

Upvotes: 1

Views: 95

Answers (1)

costaparas
costaparas

Reputation: 5237

Firstly, your directory structure looks fine. However, you should rename models/__init___.py to models/__init__.py.

As for this line:

from datasets.custom_dataset import build as build_dataset

I assume you meant:

from datasets.custom_data import build as build_dataset

since your filename is custom_data.py and not custom_dataset.py.

Finally, as for importing func inside custom_data.py, all you would need to do is this:

from models import func

inside custom_data.py.

The reason why this:

from ..models import func

doesn't work is because "relative" imports like this only work properly inside a package. Its more or less explained in this answer so I won't repeat the details here.

Hope this helps!

Upvotes: 1

Related Questions