Python: static variable decorator

前端 未结 8 686

I\'d like to create a decorator like below, but I can\'t seem to think of an implementation that works. I\'m starting to think it\'s not possible, but thought I would ask yo

8条回答
  •  -上瘾入骨i
    2021-01-06 16:14

    You could do something like that (but I haven't tested this extensively; used CPython 2.6):

    import types
    
    def static(**dict):
        def doWrap(func):
            scope = func.func_globals
            scope.update(dict)
            return types.FunctionType(func.func_code, scope)
        return doWrap
    
    # if foo() prints 43, then it's wrong
    x = 42
    
    @static(x = 0)
    def foo():
       global x
       x += 1
       print(x)
    
    foo() # => 1
    foo() # => 2
    

    It requires declaring those variables as global and shadows top-level global variables, but otherwise should work. Not sure about performance, though.

提交回复
热议问题