简体   繁体   中英

How does "as" clause affect "import" in Python?

I thought that "as" clause just makes an alias of an imported module. However, "import" fails with "as" clause in the following code.

import tensorflow.python.eager as eager

This statement raises the following error.

Traceback (most recent call last):
  File "/home/snippet/prof/importer.py", line 2, in <module>
    import tensorflow.python.eager as eager
AttributeError: module 'tensorflow' has no attribute 'python'

When I remove the "as" clause, the "import" successes. How does "as" clause affect the success and failure of "import"?

from tensorflow.python import eager

imports the name " tensorflow.python " and then gets its attribute eager , whereas

import tensorflow.python.eager as eager

imports the name " tensorflow ", and in there tries to find the attribute python , and from that the attribute eager , which it should then put in your global namespace as eager . And that's a huge difference, since there is no object python in tensorflow's __init__.py , which is what represents the tensorflow package when imported and which does not know about any subpackages that might exist. Therefore the error

AttributeError: module 'tensorflow' has no attribute 'python'

You should not have ".eager" while importing to import "eager" as something.

Try this, it will work fine:

from tensorflow.python import eager as eager

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