Why is “import *” bad?

后端 未结 12 2266
北恋
北恋 2020-11-21 06:26

It is recommended to not to use import * in Python.

Can anyone please share the reason for that, so that I can avoid it doing next time?

12条回答
  •  灰色年华
    2020-11-21 06:44

    You don't pass **locals() to functions, do you?

    Since Python lacks an "include" statement, and the self parameter is explicit, and scoping rules are quite simple, it's usually very easy to point a finger at a variable and tell where that object comes from -- without reading other modules and without any kind of IDE (which are limited in the way of introspection anyway, by the fact the language is very dynamic).

    The import * breaks all that.

    Also, it has a concrete possibility of hiding bugs.

    import os, sys, foo, sqlalchemy, mystuff
    from bar import *
    

    Now, if the bar module has any of the "os", "mystuff", etc... attributes, they will override the explicitly imported ones, and possibly point to very different things. Defining __all__ in bar is often wise -- this states what will implicitly be imported - but still it's hard to trace where objects come from, without reading and parsing the bar module and following its imports. A network of import * is the first thing I fix when I take ownership of a project.

    Don't misunderstand me: if the import * were missing, I would cry to have it. But it has to be used carefully. A good use case is to provide a facade interface over another module. Likewise, the use of conditional import statements, or imports inside function/class namespaces, requires a bit of discipline.

    I think in medium-to-big projects, or small ones with several contributors, a minimum of hygiene is needed in terms of statical analysis -- running at least pyflakes or even better a properly configured pylint -- to catch several kind of bugs before they happen.

    Of course since this is python -- feel free to break rules, and to explore -- but be wary of projects that could grow tenfold, if the source code is missing discipline it will be a problem.

提交回复
热议问题