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!
The difference between import and from import in Python is: import imports an entire code library. from import imports a specific member or members of the library.
import Python: Using the from StatementThe import statement allows you to import all the functions from a module into your code. Often, though, you'll only want to import a few functions, or just one. If this is the case, you can use the from statement.
There is a difference, because in the import x version there are two name lookups: one for the module name, and the second for the function name; on the other hand, using from x import y , you have only one lookup. As you can see, using the form from x import y is a bit faster.
Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With