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

Asked

Viewed 1,010 times

2

The 2 do the same thing (I think at least), but have always told me that import module is better then I always used this method, but the method from module import * makes the code more concise since you don’t have to keep calling the module all the time. So I wanted a more advanced opinion on this explaining why I use one or the other, thanks in advance.

  • 1

    The minireview is quite a part of your question. There is a separate stackoverflow site for this - https://codereview.stackexchange.com/ . If you can’t even post in English I think it’s okay to ask for the review here, but ask a separate question, and paste the code here (no external links)

  • ok @jsbueno already withdrew the mini-review from the question, sorry

  • not - all right you ask - I only answered in the appropriate way for this context: as a comment.

1 answer

9


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

The * removes a level of determism to your code, making some static correction check features impossible (for example, if you enter a wrong variable name, no tool will be able to point this out, since there is no way to know if the wrong name exists between what was imported with "*").

And that disrupts not only tools, but human programmers: in complex code with multiple Mports, after a week or two, you see a call function, and you can’t 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 overwrite names that had already been imported - and you won’t know that. Even worse: this over-written import could happen in a later version of a library, so that your code works when it is done, and mysteriously stops working when updating some dependency.

So: no.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.