Python keyword args can be any string

Terry Reedy tjreedy at udel.edu
Thu Feb 18 01:31:12 EST 2016


On 2/18/2016 12:59 AM, Ben Finney wrote:
> Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:
>
>> Today I learned that **kwargs style keyword arguments can be any string:
>>
>>
>> py> def test(**kw):
>> ...     print(kw)
>> ...
>> py> kwargs = {'abc-def': 42, '': 23, '---': 999, '123': 17}
>> py> test(**kwargs)
>> {'': 23, '123': 17, '---': 999, 'abc-def': 42}
>>
>>
>> Bug or feature?
>
> Incidental feature, I think.

The was discussed on pydev some years ago.  Guido says leave as is. This 
and similar cases of allowing non-identifier is string-dicts does not 
seem to cause a problem and apparently has a few rare legitimate  usages.

> If the caller is deliberately unpacking a dict, it's on them to ensure
> the keys are valid identifiers or wear the consequences.
>
> If the function cares so little about the keys in its kwargs that (as in
> your example) any string will do for each key, then it's a consenting
> actor IMO.
>
> The times when it's a problem – i.e. that the function is trying to use
> items from that dictionary as name bindings – the errors will be raised
> to the caller that unpacked that mapping. That's where the errors belong.
>


-- 
Terry Jan Reedy




More information about the Python-list mailing list