Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a decorator be working with a lambda expression at runtime? [duplicate]

Tags:

People also ask

How is the lambda expression represented by the JVM at runtime?

For Lambda expressions, the compiler doesn't translate them into something which is already understood by JVM. Lambda syntax that is written by the developer is desugared into JVM level instructions generated during compilation, which means the actual responsibility of constructing lambda is deferred to runtime.

Will lambda expression creates an object whenever it's executed?

Short answer: no.

Can a function have multiple decorators?

Multiple decorators can be chained in Python. This is to say, a function can be decorated multiple times with different (or same) decorators.

Can a Lambda function have multiple expressions?

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.


def attrs(**kwds):
      def decorate(f):
          for k in kwds:
              setattr(f, k, kwds[k])
          return f
      return decorate

@attrs(argument_types=(int, int,), returns=int)
def add(a, b):
      return a + b 

Here I need the add() can be with the ability to show its acceptable parameter type. but can I do something like this in runtime?

ladd=[]
for x in range(0,10):

      @attrs(argument_types=int, returns=int,default_parameter1 = x) 
      exp =  lambda : add(a,x)  
      ladd.append(exp)

or

ladd=[]
for x in range(0,10):

      @attrs(argument_types=int, returns=int,default_parameter1 = x) 
      addx = functools.partial(add, 2)  
      ladd.append(addx)

I need those function can be generated runtime with the "decoratored" parameter bind either


Well, here is the error information, I think above code can not work, but I never tried to paste it to python to test it...

>>> ladd=[]
>>> for x in range(0,10):
...     @attrs(argument_types=int, returns=int,default_parameter1 = x) 
...     exp =  lambda : add(a,x)  
  File "<stdin>", line 3
    exp =  lambda : add(a,x)  
      ^
SyntaxError: invalid syntax
>>>     ladd.append(exp)
  File "<stdin>", line 1
    ladd.append(exp)
    ^
IndentationError: unexpected indent
>>>