Is "from ... import ..." sometimes required and plain "import ..." not always working? Why?

dynobo :

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!

user2357112 supports Monica :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=5278&siteId=1