Is “from … import …” sometimes required and plain “import …” not always working? Why?

筅森魡賤 提交于 2021-02-05 05:12:13

问题


I always thought, doing from x import y and then directly use y, or doing import x and later use x.y was only a matter of style and avoiding naming conflicts. But it seems like this is not always the case. Sometimes from ... import ... seems to be required:

Python 3.7.5 (default, Nov 20 2019, 09:21:52)
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import PIL
>>> PIL.__version__
'6.1.0'
>>> im = PIL.Image.open("test.png")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'PIL' has no attribute 'Image'
>>> from PIL import Image
>>> im = Image.open("test.png")
>>>

Am I doing something wrong here?

If not, can someone please explain me the mechanics behind this behavior? Thanks!


回答1:


For submodules, you have to explicitly import the submodule, whether or not you use from. The non-from import should look like

import PIL.Image

Otherwise, Python won't load the submodule, and the submodule will only be accessible if the package itself imports the submodule for you or if some previous code has explicitly imported the submodule.



来源:https://stackoverflow.com/questions/60242370/is-from-import-sometimes-required-and-plain-import-not-always-wo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!