[Python-Dev] Fwd: deep question re dict as formatting input
Eric Smith
eric at trueblade.com
Wed Feb 23 13:10:04 CET 2011
On 02/22/2011 07:32 PM, 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".
>
> See find_name_split in Objects/stringlib/string_format.h, in particular
> the call to get_integer() and the interpretation of the result.
Just for the archives, I'll mention why it works this way. It's trying
to support indexing by integers, as well as dictionary access using
arbitrary keys. Both of course use the same syntax.
In this case it must convert the index values into ints:
>>> a = ['usr', 'var']
>>> '{0[0]} {0[1]}'.format(a)
'usr var'
And in this case it doesn't:
>>> a = {'one':'usr', 'two':'var'}
>>> '{0[one]} {0[two]}'.format(a)
'usr var'
Eric.
More information about the Python-Dev
mailing list