Injecting variables into the caller's scope?

前端 未结 3 437
故里飘歌
故里飘歌 2020-12-25 15:29

Can I define a function which, when called, inserts new locals into the caller\'s scope? I have a feeling that passing the caller\'s locals() into the function migh

3条回答
  •  余生分开走
    2020-12-25 16:05

    This is not possible without changing the API, as CPython retains a reference to the argument list for the duration of the function call.

    One way to do this is to pass an object, and clear the object's internal state when done using it.

    class Obj(object):
        def __init__(self, state):
            self.state = state
    
    def f(o):
        # Do stuff with o.state
        del o.state
    

提交回复
热议问题