How to apply decorators to lambdas?

后端 未结 2 1245
-上瘾入骨i
-上瘾入骨i 2020-12-10 01:03

Is there any syntax for using a decorator on a lambda function in Python? Example:

def simpledecorator(f):
     def new_f():
         print \"Using a decorat         


        
相关标签:
2条回答
  • 2020-12-10 01:26

    There appear to be two options which give the functionality, but without the clean syntax:

    (1) Keep lambda and ditch the decorator syntax (as posted by dan04):

    f = simpledecorator( lambda : print( "Hello World" ) )

    (2) Keep the decorator syntax and use a 1 line def statement instead of lambda:

    @simpledecorator
    def f(): print ( "Hello World" )
    
    

    This 2nd form may be preferable if you want to chain decorators:

    @simpledecorator
    @simpledecorator
    def f(): print ( "Hello World" )
    
    
    0 讨论(0)
  • 2020-12-10 01:33
    f = anotherdecorator(lambda x: x * 2)
    
    0 讨论(0)
提交回复
热议问题