[Python-Dev] Fwd: deep question re dict as formatting input
Ethan Furman
ethan at stoneleaf.us
Wed Feb 23 19:18:58 CET 2011
Eric Smith wrote:
> 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".
Given the representation issues with floating point, I think the current
behavior is desirable. Also, leaving digits with periods as strings
would, I think, be more useful (Dewey Decimal, anyone?).
~Ethan~
More information about the Python-Dev
mailing list