Reputation: 244
Why am I able to do this in Python 3.7:
from PIL import Image
im = Image.open("hardcastle-crags-3462894.jpg")
But not this, which I had understood to be the same thing:
import PIL
im = PIL.Image.open("hardcastle-crags-3462894.jpg")
The latter gives result:
AttributeError: module 'PIL' has no attribute 'Image'
I had understood these to be the same thing. Why does one work and the other does not?
Upvotes: 5
Views: 10930
Reputation: 244
To answer my own question (now that I understand properly).
In Python, you can import:
In this case, the statement:
import PIL
Is really the same as saying "import the __init__.py file in the PIL directory". In this specific case, that __init__.py file does not import or otherwise make available any class or other module called "Image", so my subsequent reference to it in example 2 in my initial post import fails.
In contrast, the statement:
from PIL import Image
is interpreted a bit differently. This is really the same as saying "look in the package directory PIL for a module called Image and import it".
So you can see that the import statement is actually a bit context dependent. It can mean different things in different circumstances.
This is an excellent resource that explains the different ways in which the import statement can function depending on context.
Upvotes: 7