How to modify the local namespace in python

前端 未结 7 516
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 19:39

How can I modify the local namespace of a function in python? I know that locals() returns the local namespace of the function when called inside it, but I want to do somet

7条回答
  •  渐次进展
    2020-12-01 20:32

    A function that's not executing doesn't have any locals; the local context is created when you run the function, and destroyed when it exits, so there's no "local namespace" to modify from outside the function.

    You can do something like this, though:

    def f():
        g = [1]
        def func():
            print g[0]
        return func, g
    
    f, val = f()
    f()
    val[0] = 2
    f()
    

    This uses an array to simulate a reference.

提交回复
热议问题