[PyQt] from PyQt5.Qt import *

Kyle Altendorf sda at fstab.net
Thu Jun 28 12:27:34 BST 2018


On 2018-06-28 01:25, Zhao Lee wrote:
> but now I could replace all of them with only " from PyQt5.Qt import * 
> "

> any drawback along with the single line import ?

The doc you linked explained the memory cost of importing anything via 
the PyQt5.Qt module.  There are additional reasons that from imports are 
somewhat risky and * imports are generally fairly questionable.

When you `from x import y` you are making a new name (`y`) referencing 
the object referenced by `x.y` at that point in time.  Generally, module 
globals (such as `y` in this example) should not be reassigned but it 
can and does happen.  Then when you use `y` you will still get the old 
object, not the new.

https://repl.it/@altendky/why-not-to-from-import

`from x import *` has the same issue, but additionally people reading 
the code don't know where names came from.  With a single `import *` 
it's annoying, with two...  we end up having to add diagnostics to the 
code and run it ourselves to figure out where the otherwise unknown 
variables came from.  Dumping things into the module scope with this 
hazards some confusing behavior with some packages like numpy that have 
lots of things with fairly 'normal' names in them.  You end up with 
collisions and some names being unexpectedly overwritten possibly 
depending on the order of imports.

Admittedly, Qt suffers from mostly the opposite namespacing issue in 
that you end up triple namespaced because each layer of 
PyQt5.QtWidgets.QApplication has the indicative Q in it.  Still, these 
problems are generally relevant to `from` and `*` imports.

Cheers,
-kyle


More information about the PyQt mailing list