[Python-Dev] Fwd: deep question re dict as formatting input
Eric Smith
eric at trueblade.com
Wed Feb 23 01:32:56 CET 2011
On 2/22/2011 6:28 PM, Steve Holden wrote:
>
> On Feb 22, 2011, at 3:08 PM, Eric Smith wrote:
>
>> Quoting PEP 3101:
>>
>> An example of the 'getitem' syntax:
>>
>> "My name is {0[name]}".format(dict(name='Fred'))
>>
>> It should be noted that the use of 'getitem' within a format string
>> is much more limited than its conventional usage. In the above example,
>> the string 'name' really is the literal string 'name', not a variable
>> named 'name'. The rules for parsing an item key are very simple.
>> If it starts with a digit, then it is treated as a number, otherwise
>> it is used as a string.
>>
> That's not strictly true:
>
>>>> d = {"Steve":"Holden", "Guido":"van Rossum", 21.2:"float"}
>>>> d[21.1]
> Traceback (most recent call last):
> File "<stdin>", line 1, in<module>
> KeyError: 21.1
>>>> d[21.2]
> 'float'
>>>> "{0[21.2]}".format(d)
> Traceback (most recent call last):
> File "<stdin>", line 1, in<module>
> KeyError: '21.2'
>>>>
You are correct, I didn't exactly implement the PEP on this point,
probably as a shortcut. I think there's an issue somewhere that
discusses this, but I can't find it. The CPython implementation is
really using "If every character is a digit, then it is treated as an
integer, otherwise it is used as a string".
See find_name_split in Objects/stringlib/string_format.h, in particular
the call to get_integer() and the interpretation of the result.
Eric.
More information about the Python-Dev
mailing list