Use from module import * vs use import module in python 3

2

The two do the same thing (I think at least), but I've always been told that import module is better so I've always used this method, but the / strong> leaves the code more concise since you do not have to be calling the module all the time. So I wanted a more advanced opinion about this explaining why to use one or the other, thank you right away.

    
asked by anonymous 29.10.2017 / 16:45

1 answer

5

Never use from module import * . The "conciseness" in this case is an illusion.

* removes a level of determinism for your code, making some static correction check functionality impossible (for example, if you enter a wrong variable name, no tool will be able to point this out, since it does not have how to tell if the wrong name exists between what was imported with "*").

And this is not only the tools, as human programmers: in a complex code with several imports, after a week or two, you see a call to the function, and can not know where it came from, for example

And it's even dangerous: if you have more than one import with "*" in the same module, an import that comes after could overlap names that had already been imported - and you will not know how. Worse still: this overwriting of import could happen in a later version of a library, so that its code works when it's done, and mysteriously stops working when you upgrade some dependency.

Then: No.

As for "conciseness," it is relative. The syntax of import in Python is very flexible, and you probably can maintain this concision even without introducing the ambiguity of * : you can import only the names that some module needs, for example from modulo import metodo1, metodo2 or, in the case of a module of which you are going to call a lot, just use a smaller name for it, such as import numpy as np or import typing as T .

    
29.10.2017 / 18:12