What do @ and lambda mean in Python?

Possible Duplicate:
Understanding Python decorators

Just trying to "port" some Python code to Java, I came then across the following python code:

 @fake(lambda s, t, n: [(s.field(i+1), s) for i in range(n)])
 def split(secret, threshold, num_players):
     shares = []
     for i in range(1, num_players+1):
         # do some shares calculation
     return shares

There are quite some interesting constructs in this one that I never noticed before. Could anyone tell me what is the deal with this @fake thingy?

def fake(replacement):
    """Replace a function with a fake version."""
    def decorator(func):
        fakes = os.environ.get('FUNC_FAKE', '')
        if fakes == '*' or func.__name__ in fakes.split():
            return replacement
        else:
            return func
    return decorator

Further, does this lambda stand for a function name or what is the deal with that?


First of all, @fake is a decorator.

What @fake appears to do is to conditionally replace the function that follows, ie split , with the lambda function (note how the two take the same parameters).

The decision is based on the FUNC_FAKE environment variable. If the latter equals * or contains split as one of its tokens, the replacement is made. Otherwise, it isn't.

The fact that the replacement is a lambda function is not important. It could have just as easily been made into a normal function:

def split_replacement(s, t, n):
   return [(s.field(i+1), s) for i in range(n)])

@fake(split_replacement)
def split(s, t, n):
   ...

This whole construct is rather baffling. I struggle to come up with a reason for doing things this way, other than to try and confuse other programmers (or to play with decorators).


The first question is answered elsewhere.

For your second question:

x = lambda a, b, *args, **kwargs: <expression>

is just a shorthand for

def x(a, b, *args, **kwargs):
    return <expression>

See also here.

链接地址: http://www.djcxy.com/p/23800.html

上一篇: Python装饰器是做什么的,它的代码在哪里?

下一篇: 在Python中@和lambda是什么意思?