Why is “import *” bad?

后端 未结 12 2234
北恋
北恋 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:54

    As suggested in the docs, you should (almost) never use import * in production code.

    While importing * from a module is bad, importing * from a package is probably even worse.

    By default, from package import * imports whatever names are defined by the package's __init__.py, including any submodules of the package that were loaded by previous import statements.

    If a package’s __init__.py code defines a list named __all__, it is taken to be the list of submodule names that should be imported when from package import * is encountered.

    Now consider this example (assuming there's no __all__ defined in sound/effects/__init__.py):

    # anywhere in the code before import *
    import sound.effects.echo
    import sound.effects.surround
    
    # in your module
    from sound.effects import *
    

    The last statement will import the echo and surround modules into the current namespace (possibly overriding previous definitions) because they are defined in the sound.effects package when the import statement is executed.

提交回复
热议问题