Python function replacing itself in the module namespace

This question already has an answer here:

  • Using global variables in a function other than the one that created them 18 answers

  • If you go without the global statement, you will be creating a local variable with the name _run_wsgi_app , and then will use it, but nothing will change in the global namespace. Using global _run_wsgi_app you ensure that you are re-binding the global name to the new function.

    Remember the basic usage of global :

    def foo():
        x = 2
    def bar():
        global x
        x = 3
    
    x = 1
    print(x) # --> 1
    foo()
    print(x) # --> 1
    bar()
    print(x) # --> 3
    

    Your example is the same, but instead of binding the name directly with name = ... , it does with from ... import ... as name .

    An alternative way to redefine itself without global is to use the module object where it is contained.

    def _run_wsgi_app(*args):
        from werkzeug.test import run_wsgi_app as new_run_wsgi_app
        import sys
        sys.modules[__name__]._run_wsgi_app = new_run_wsgi_app
        return new_run_wsgi_app(*args)
    
    链接地址: http://www.djcxy.com/p/23900.html

    上一篇: 在Python中为多个函数创建单个TELNET对象

    下一篇: Python函数在模块名称空间中替换它自己