How to dynamically modify a function's local namespace?

后端 未结 3 1035
走了就别回头了
走了就别回头了 2021-01-13 17:11

NB: This question assumes Python 2.7.3.

I\'m looking for a sane approach to dynamically modify a function\'s local namespace, preferably in a way that adds the lea

3条回答
  •  一个人的身影
    2021-01-13 18:11

    May be something like that

    def foo():
        print(x)
    
    foo.__globals__["x"] = "Hello Python"
    
    foo()
    

    unfortunately this does not works in body of function if varible has been defined

    def foo(flag):
        x = "Hello World"
        if flag:
            foo.__globals__["x"] = "Hello Python"
    
        print(x)
    

    prints Hello World in both flag is True or False

提交回复
热议问题