Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a complete list of built-in functions that cannot be called with keyword argument?

People mentioned in answers a1, a2 that

Due to the way the Python C-level APIs developed, a lot of built-in functions and methods don't actually have names for their arguments.

I found it really annoying cause I'm not be able to know it by looking at the doc. For instance, eval

eval(expression, globals=None, locals=None)

Then I wrote this line of code

print(eval('a+b', globals={'a':1, 'b':2}))

and got TypeError: eval() takes no keyword arguments. So is there a complete list of functions of this kind? How do I know if a function is allowed to have keyword arguments?

like image 384
laike9m Avatar asked Apr 14 '16 08:04

laike9m


1 Answers

In Python 3.5 you can inspect the __text_signature__ of the built-in function:

>>> eval.__text_signature__
'($module, source, globals=None, locals=None, /)'

or

>>> abs.__text_signature__
'($module, x, /)'
>>> abs(x=5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: abs() takes no keyword arguments

(x cannot be used as a keyword argument)

The / means that the arguments following that can be used as keyword arguments. C.f.

>>> compile.__text_signature__
'($module, /, source, filename, mode, flags=0,\n        dont_inherit=False, optimize=-1)'
>>> compile(source='foo', filename='bar', mode='exec')
<code object <module> at 0x7f41c58f0030, file "bar", line 1>

Of course there are bugs even in 3.5:

>>> sorted.__text_signature__
'($module, iterable, key=None, reverse=False)'

though according to issue 26729 in the Python bug tracker, there ought to be / after the iterable as the iterable cannot be used as a keyword argument.


Unfortunately this information is not yet available in the Python documentation itself.

like image 123


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!