Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`from x import y` vs. `from x.y import *`

Tags:

python

What is the difference between these two lines?

from PyQt4 import QtGui
from PyQt4.QtGui import *

The first line is "import QtGui class from module PyQt4".
But what does second line means? "Import everything from QtGui of module PyQt4".
Is not it the same?

like image 749
Qiao Avatar asked Jan 08 '11 17:01

Qiao


People also ask

What is the difference between import X and from X import *?

The difference between import and from import in Python is: import imports the whole library. from import imports a specific member or members of the library.

What is from X import Y in Python?

from x import y will only import y from module x . This way, you won't have to use dot-notation. (Bonus: from x import * will refer to the module in the current namespace while also replacing any names that are the same) import x as y will import module x which can be called by referring to it as y.

What is the meaning of from X import *?

from X import * imports all elements from the module X into the current namespace.

What is the difference between from and import in Python?

use import most of the time, but use from is you want to refer to the members of a module many, many times in the calling code; that way, you save yourself having to write "feather." (in our example) time after time, but yet you don't end up with a cluttered namespace.


1 Answers

First statement imports the specified module into the current namespace.
Second statement imports everything from the specified module into the current namespace.

So 1) means you still need to explicitly reference any classes/functions etc through the module namespace
2) Means you don't

Here's a compare and contrast that shows the difference

1)

import math

d = math.sqrt(10)

2)

from math import *

d = sqrt(10)

Note that you can choose to import a specific symbol from a module if you want i.e.

from math import sqrt
d = sqrt(10)
like image 189
zebrabox Avatar answered Sep 22 '22 02:09

zebrabox