[Python-Dev] Very Strange Argument Handling Behavior
Nick Coghlan
ncoghlan at gmail.com
Sat Apr 17 11:33:33 CEST 2010
Steve Holden wrote:
> I'm sure we wouldn't want to go so far as to inhibit this. (Py 3.1)
>
>>>> def f(**kwargs):
> ... kwargs[1] = "dummy"
> ... print(kwargs)
> ...
>>>> f(this="Guido", that="Raymond", the_other="Steve")
> {'this': 'Guido', 1: 'dummy', 'the_other': 'Steve', 'that': 'Raymond'}
>
> Or would we? If it's OK to mutate kwargs inside the function to contain
> a non-string key, why isn't it OK to pass a non-string key in?
Because we can easily enough add the kwargs type check to CPython to
improve cross-implementation compatibility, while we can't easily check
individual assignments.
> I understand that it couldn't be generated using keyword argument
> syntax, but I don't see why we discriminate against f(**dict(...)) to
> limit it to what could be generated using keyword argument syntax. Is
> this such a big deal?
The language spec is intended to allow the use of string-only
dictionaries for namespaces. CPython happens to use normal dictionaries
and then optimises them heavily when they only contain string keys, but
other implementations are meant to be allowed to use a separate type
that doesn't permit arbitrary keys.
In cases where it is easy for CPython to check for purely string keys,
that's probably worth doing (especially now it has been noted that the
common case of that check passing can be made fast using the existing
string keys only optimisation tools).
There's also a consistency argument here, in that CPython already
performs this check for Python functions, so it is anomalous that there
are ways to do this without triggering the TypeError.
More exotic namespace abuse is generally harder to detect, and almost
certainly not worth the hassle of flagging on CPython itself (such code
will still fail on implementations that actually use string-key only
namespaces).
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
More information about the Python-Dev
mailing list