What do @ and lambda mean in Python?
Question: > **Possible Duplicate:**  
>  [Understanding Python
> decorators](http://stackoverflow.com/questions/739654/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?


Answer: First of all, `@fake` is a
[decorator](http://stackoverflow.com/questions/739654/understanding-python-
decorators).

What `@fake` appears to do is to conditionally replace the function that
follows, i.e. `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](http://www.diveintopython.net/power_of_introspection/lambda_functions.html)
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).

