Why is “import *” bad?

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

    That is because you are polluting the namespace. You will import all the functions and classes in your own namespace, which may clash with the functions you define yourself.

    Furthermore, I think using a qualified name is more clear for the maintenance task; you see on the code line itself where a function comes from, so you can check out the docs much more easily.

    In module foo:

    def myFunc():
        print 1
    

    In your code:

    from foo import *
    
    def doThis():
        myFunc() # Which myFunc is called?
    
    def myFunc():
        print 2
    

提交回复
热议问题