Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 343
dynobo Avatar asked Feb 15 '20 19:02

dynobo


People also ask

What is the difference between from import and import?

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.

What is from and import in Python?

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.

Which is faster import or from import?

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.

Why is the use of import all statements not recommended?

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.


1 Answers

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.

like image 121
user2357112 supports Monica Avatar answered Nov 15 '22 00:11

user2357112 supports Monica