I’m having problems in importing a module.
If I use,
import fruit as f
print f.apple.juice.CALORIES_INT
This works.
And
import fruit.apple.juice as j
print j.CALORIES_INT
Doesn’t work. It throws AttributeError: 'module' object has no attribute 'apple'. Any suggestion on how to debug it?
My directory structure looks like:
fruit
--- __init__.py
--- apple
---------__init__.py
--------- juice.py
---------------CALORIES_INT is a variable declared here
--- orange
--------- __init__.py
--------- shake.py
---------------trying to access CALORIES_INT here by importing it.
apple is a package. I am able to import other package though.
You need to add
from . import appleto the__init__.pyfile of yourfruitpackage. Alternatively, you could usefrom fruit import applein the same location.Nested packages are not automatically made available as attributes of the parent package, this only works after importing the nested package explicitly.
If you first to
import fruit.apple, thenimport fruit; fruit.appleworks. Or you explicitly import theapplenested package in thefruit/__init__.pyfile to ensure thatimport fruit; fruit.applealways works for users of yourfruitpackage.The same applies to the
juicemodule in theapplepackage; you need to make it available by importing it in theapplepackage__init__.py; add afrom . import juice, or use an absolute import likefrom fruit.apple import juice.