问题
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