[Python-ideas] Why does BoundArguments use an OrderedDict?

Antony Lee antony.lee at berkeley.edu
Wed Dec 17 02:24:37 CET 2014

Currently, BoundArguments stores the results of signature.bind (and
bind_partial) in an OrderedDict.  Given that there is no way to retrieve
the order in which keyword arguments were passed, it is not surprising that
the dict ordering is based on the order of parameters in the signature, not
the order in which arguments are passed (although this point could
certainly be made clearer in the docs).  But this also means that that
ordering could easily be retrieved by iterating over the parameters
("[(name, ba.arguments[name]) for name in ba.signature.parameters if name
in ba.arguments]"), and signature.bind now has to pay for the cost of using
a Python-implemented OrderedDict.

Obviously, one solution would be to switch to a C-implemented OrderedDict,
but another simpler one would simply to make BoundArguments.arguments a
regular dict rather than an OrderedDict (which is a one-line patch,
changing the definition of "arguments" in Signature._bind).  A simple test
on the example below show approximately a two-fold faster "bind".

from inspect import signature
s = signature(lambda x, y=1, *, z: None)
for _ in range(30000):
    s.bind(1, z=2)
    s.bind(1, 3, z=2)
    s.bind(x=1, z=2, y=3)
    try: s.bind(1)
    except TypeError: pass
    try: s.bind()
    except TypeError: pass
    try: s.bind(1, y=2)
    except TypeError: pass

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141216/ce19a190/attachment.html>

More information about the Python-ideas mailing list