Why is “import *” bad?

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

    As a test, I created a module test.py with 2 functions A and B, which respectively print "A 1" and "B 1". After importing test.py with:

    import test
    

    . . . I can run the 2 functions as test.A() and test.B(), and "test" shows up as a module in the namespace, so if I edit test.py I can reload it with:

    import importlib
    importlib.reload(test)
    

    But if I do the following:

    from test import *
    

    there is no reference to "test" in the namespace, so there is no way to reload it after an edit (as far as I can tell), which is a problem in an interactive session. Whereas either of the following:

    import test
    import test as tt
    

    will add "test" or "tt" (respectively) as module names in the namespace, which will allow re-loading.

    If I do:

    from test import *
    

    the names "A" and "B" show up in the namespace as functions. If I edit test.py, and repeat the above command, the modified versions of the functions do not get reloaded.

    And the following command elicits an error message.

    importlib.reload(test)    # Error - name 'test' is not defined
    

    If someone knows how to reload a module loaded with "from module import *", please post. Otherwise, this would be another reason to avoid the form:

    from module import *
    

提交回复
热议问题