Python: static variable decorator

前端 未结 8 681

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:28

    A slight tweak of another anwser:

    def static(**kwargs):
        def decorator(func):
            return type(func)(func.func_code, dict(func.func_globals, **kwargs))
        return decorator
    
    message = "goodbye, world!"
    @static(message="hello, world!")
    def hello(): print message
    
    hello()
    

    I found it icky to override a builtin name with a function argument name, so I changed **dict into the more canonical **kwargs. I also saved a few lines and IMO made the code cleaner by constructing a new dict with dict(the_original, **the_updates). Lastly I saved a few lines by accessing the function constructor via type(func) rather than an import---type and class objects are factory methods, so use them!

    I also removed a global declaration. This works as long as you don't rebind the variable, i.e. removing global in effect makes the pointer (but not the object) read-only. If you use it this way, maybe let is a better name than static for the binding thus introduced.

    0 讨论(0)
  • 2021-01-06 16:29

    Here's something that might be much clearer. It doesn't involve any decorators or hacking.

    class F( object ):
        def __init__( self ):
            self.x= 0
        def __call__( self ):
            self.x += 1
            print self.x
    
    f= F()
    

    Now you have your function f with a static variable.

    f() #prints 1
    f() #prints 2
    
    0 讨论(0)
提交回复
热议问题