python - Please explain why these two builtin functions behave different when passed in keyword arguments -


consider these different behaviour::

>> def minus(a, b): >>    return - b  >> minus(**dict(b=2, a=1)) -1  >> int(**dict(base=2, x='100')) 4  >> import operator >> operator.sub.__doc__ 'sub(a, b) -- same - b.' >> operator.sub(**dict(b=2, a=1)) typeerror: sub() takes no keyword arguments 

why operator.sub behave differently int(x, [base]) ?

it implementation detail. python c api retrieve arguments separates between positional , keyword arguments. positional arguments not have name internally.

the code used retrieve arguments of operator.add functions (and similar ones sub) this:

pyarg_unpacktuple(a,#op,2,2,&a1,&a2) 

as can see, not contain argument name. whole code related operator.add is:

#define spam2(op,aop) static pyobject *op(pyobject *s, pyobject *a) { \   pyobject *a1, *a2; \   if(! pyarg_unpacktuple(a,#op,2,2,&a1,&a2)) return null; \   return aop(a1,a2); }  spam2(op_add           , pynumber_add) 
#define spam2(op,altop,doc) {#op, op_##op, meth_varargs, pydoc_str(doc)}, \                            {#altop, op_##op, meth_varargs, pydoc_str(doc)}, spam2(add,__add__, "add(a, b) -- same + b.") 

as can see, place a , b used in docstring. method definition not use meth_keywords flag necessary method accept keyword arguments.

generally spoken, can safely assume python-based function know argument name always accept keyword arguments (of course nasty stuff *args unpacking creating function doc arguments normal) while c functions may or may not accept keyword arguments. chances functions more few arguments or optional arguments accept keyword arguments later/optional ones. pretty have test it.

you can find discussion supporting keyword arguments everywhere on python-ideas mailinglist. there statement guido van rossum (the benevolent dictator life aka creator of python) on it:

hm. think many (most?) 1-arg , selected 2-arg functions (and 3+-arg functions) reduce readability, example of ord(char=x) showed.

i see syntactic feature state argument cannot given keyword argument (just added syntax state must keyword).

one area think adding keyword args outright wrong: methods of built-in types or abcs , overridable. e.g. consider pop() method on dict. since argument name undocumented, if subclasses dict , overrides method, or if create mutable mapping class tries emulate dict using duck typing, doesn't matter argument name -- callers (expecting dict, dict subclass, or dict-like duck) using positional arguments in call. if document argument names pop(), , users started use these, dict sublcasses , ducks broken (except if luck happened pick same name).


Comments

Popular posts from this blog

How do you change vbulletin's home page to the forums instead of the default (CMS or Activity Stream)? -

c++ - Troubles when compiling phash program -