user5779223 user5779223 - 4 months ago 9
Python Question

__init__ file doesn't work as expected in python

I have some folders and

.py
files in the following structure:

parent/
__init__.py
test.ipynb
code/
__init__.py
common.py
subcode/
__init__.py
get_data.py


In the
__init__
file under the
parent
folder, I have
import code
and in the one of
code
, I have
import subcode
. But when I tried
import code.subcode
, I got such an error:

ImportError: No module named 'code.subcode'; 'code' is not a package


But when I just
import code
, no error is thrown. However, when I call
code.subcode
, this error happens:

AttributeError: module 'code' has no attribute 'subcode'


I try all of those mentioned above in the
test.ipynb
, which is at the root of the directory.

Do you know what is the reason and how can I fix it? Thanks!

Answer

The problem is that you are importing another module named code that is installed on your system rather than your own module. You can verify this by checking the module file path in code.__file__ after you import code.

The first thing to do is change the name of your module to avoid namespace collisions with the other code package on your system. If your new package name doesn't collide with something else, you should now either successfully be importing it and have it behave as expected, or it fails to import entirely.

If it fails to import, it is most likely because your parent directory is not in your PYTHONPATH environment variable.

There can potentially also be other more technical reasons that a module is not recognized by the interpreter such as old definitions being cached (in which case restarting the interpreter is often enough. Possibly after deleting any precompiled versions of the module). Another problem I have seen ended up being that a module contained a bug that made the interpreter unable to parse it. I am sure there are other odd possibilities out there.