Why is “import *” bad?

后端 未结 12 2280
北恋
北恋 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

    It is a very BAD practice for two reasons:

    1. Code Readability
    2. Risk of overriding the variables/functions etc

    For point 1: Let's see an example of this:

    from module1 import *
    from module2 import *
    from module3 import *
    
    a = b + c - d
    

    Here, on seeing the code no one will get idea regarding from which module b, c and d actually belongs.

    On the other way, if you do it like:

    #                   v  v  will know that these are from module1
    from module1 import b, c   # way 1
    import module2             # way 2
    
    a = b + c - module2.d
    #            ^ will know it is from module2
    

    It is much cleaner for you, and also the new person joining your team will have better idea.

    For point 2: Let say both module1 and module2 have variable as b. When I do:

    from module1 import *
    from module2 import *
    
    print b  # will print the value from module2
    

    Here the value from module1 is lost. It will be hard to debug why the code is not working even if b is declared in module1 and I have written the code expecting my code to use module1.b

    If you have same variables in different modules, and you do not want to import entire module, you may even do:

    from module1 import b as mod1b
    from module2 import b as mod2b
    

提交回复
热议问题