Python: static variable decorator

前端 未结 8 888

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条回答
  •  天命终不由人
    2021-01-06 16:05

    Here is a really simple solution that works just like normal python static variables.

    def static(**kwargs):
      def wrap(f):
        for key, value in kwargs.items():
          setattr(f, key, value)
        return f
      return wrap
    

    Example usage:

    @static(a=0)
    def foo(x):
      foo.a += 1
      return x+foo.a
    
    foo(1)  # => 2
    foo(2)  # => 4
    foo(14) # => 17
    

    This more closely matches the normal way of doing python static variables

    def foo(x):
      foo.a += 1
      return x+foo.a
    foo.a = 10
    

提交回复
热议问题