How to modify the local namespace in python

前端 未结 7 531
爱一瞬间的悲伤
爱一瞬间的悲伤 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:27

    Since the function isn't invoked, it has no "local" stack frame, yet. The most simple solution is to use a global context:

    handler = None
    def f():
        handler()
    
    def g(): pass
    
    handler = g
    

    Or you could set g on the function object:

    f.g = g
    

    But I'm not sure how you can get the function object from within the function itself. If it was a method, you would use self.

提交回复
热议问题