简体   繁体   中英

Strange behavior in import

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 apple from . import apple to the __init__.py file of your fruit package. Alternatively, you could use from fruit import apple in 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 , then import fruit; fruit.apple import fruit; fruit.apple works. Or you explicitly import the apple nested package in the fruit/__init__.py file to ensure that import fruit; fruit.apple import fruit; fruit.apple always works for users of your fruit package.

The same applies to the juice module in the apple package; you need to make it available by importing it in the apple package __init__.py ; add a from . import juice from . import juice , or use an absolute import like from fruit.apple import juice .

尝试:

 from fruit.apple import juice as j

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM