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,
@fakeis a decorator.What
@fakeappears 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_FAKEenvironment variable. If the latter equals*or containssplitas 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:
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).