__init__.py can’t find local modules

Put the following codes in the __init__.py inside the Animals directory.

Python 3.x :

from .Mammals import Mammals
from .Birds import Birds

On 2.x:

from __future__ import absolute_import
from .Mammals import Mammals
from .Birds import Birds

Explanation:

It can’t find the module because it doesn’t know what directory to search to find the files Mammals and Birds. You’re assuming that the subfolder Animals gets added to the python search path, but if you check sys.path (executed from Projects/Animals/__init__.py) you’ll see that only the path to Project is on the path. I’m not sure why the directory containing Project/Animals/__init__.py is not searched, since that’s the code being executed, but the error indicates this is the cause.

Putting a . before the module name tells Python that the module you’re loading is inside the current module’s directory.

(Thanks to @SeanM’s comment for explaining.)

Leave a Comment

tech