def validate(request, *args, **kwargs):
form_class = kwargs.pop('form_class')
extra_args_func = kwargs.pop('callback', lambda request, *args, **kwargs: {})
thanks
a={'a':'aaa','b':'bbb'}
b=a.pop('a',lambda x,y:x)
print a
i k开发者_如何学运维now dict.pop('a'),but i don't know dict.pop('a',func) what is the use of 'func‘ in here
The expression:
lambda request, *args, **kwargs: {}
builds an anonymous function which must be called with at least one argument (which, if named, must be named request) and can be called with any number of positional and named arguments: when called, it ignores all the arguments and returns a new empty dictionary.
The code snippet:
a={'a':'aaa','b':'bbb'}
b=a.pop('a',lambda x,y:x)
print a
prints {'b': 'bbb'} (which is also the value a stays bound this after the snippet executes) and bings the string 'aaa' to name b. The second argument to the .pop method plays no role in this case: it's only used when the first argument is not found as a key in the dictionary on which the method is called (in which case, .pop's second argument would be the "default value" returned by the call to .pop, without any alteration to the dictionary). In this case, 'a' is indeed found at that time as a key in dictionary a, and therefore it's removed from that dictionary, and the corresponding value, string 'aaa', is returned by the call to .pop (whence it gets then bound to name b).
That is a "lambda function". It's a short way of expressing a function that's declared inline. It looks like this:
lambda arg1,arg2,...: expression
and is the equivalent of a nameless function that would look like this:
def some_nameless_function(arg1,arg2,...):
return expression
So, the code you have there,
def validate(request, *args, **kwargs):
form_class = kwargs.pop('form_class')
extra_args_func = kwargs.pop('callback', lambda request, *args, **kwargs: {})
is equivalent to a function that looks like this:
def nameless_function(request, *args, **kwargs):
return {}
def validate(request, *args, **kwargs):
form_class = kwargs.pop('form_class')
extra_args_func = kwargs.pop('callback', nameless_function)
What it's doing is pop off a callback function from the kwargs dict, or if that isn't set, it creates a lambda function that does nothing (returns an empty dict). The request, *args, **kwargs part is presumably the "signature" of the callback function.
加载中,请稍侯......
精彩评论