Time is exactly the same -
the difference is in the readability that your own code will have -
In the example you set yourself
from biblioteca import *
...
# 300 linhas depois
...
for elemento in a:
fca_coisas(elemento, b)
So - where did "a" and "b" ?
When you import elements with the specific name both who is reading your code (in general yourself), and the programming tools, such as Ides and code linters, can know where each name (variable, class or module) you are using in your code came from.
A single from x import *
ends the functionality of any tool that lets you know if you are using a non-existent variable, for example - since the tool has no way of knowing if the name you typed was not imported along with the *
In Python 3 inclusive, for the sake of optimizing access to local variables in the standard implementation, became syntax error wear a from x import *
within a function - because that way the compiler has no way of knowing, before executing the code, what will be the local variables of the function, and which it would have to search for as non-local or global variables.
Clarified this, we will see your specific doubts:
- It is correct to say that to import from a module only that which goes
use is more performatic than using the asterisk?
Not.
- Or it doesn’t make
any difference in Python?
This makes no difference in Python - anyway the target module is compiled in full - even if it has 300 function statements and you will only use one. (but of course, there are several ways to write the code that, if that’s going to make a difference - and almost never will - you can actually just compile and import what you’re going to need).
- It’s a good idea to use *, even if
there are things being imported, which I will not use?
It’s never a good idea to use the *
. Or almost never - there are exceptions, such as libraries that expose constants or names for interactive work.
Code examples with Pyqt, Numpy and Pygame often comes with from x import *
- but even so, for a medium-sized project, it’s worth using import nome_grande_da_biblioteca as x
, and access things as x.CONSTANTE, x.funcao_1
- than using the *
.
- There is a
performance difference between form import library * and import
library?
No. Except for an import within a Python 2.x function - in this case, any code in a function that contains a import *
will be slower, because Python can not optimize access to local variables.
@Renan in the specific case, I want to make a stubborn strip between these two. But since you’ve touched on the subject, I’ll make a :p edition
– Wallace Maxters