[Python-3000] Nested brackets (Was: Please don't kill the % operator...)

"Martin v. Löwis" martin at v.loewis.de
Fri Aug 17 18:17:48 CEST 2007


>> On second thought, that won't work.  For example, this currently
>> doesn't work:
>> '{0[{foo}{bar}]}'.format({'FOOBAR': 'abc'}, foo='FOO', bar='BAR')
>> KeyError: 'FOO'
>>
>> I can't decide if that's a bug or not.
> 
> I think it will be a bug.  Some one is bound to run into it at some
> point if they are using nested braces routinely.  Although most people
> never will, so it may be a limitation we can live with.

OK, I think both the PEP and the understanding must get some serious
tightening.

According to the PEP, "The rules for parsing an item key are very
simple" - unfortunately without specifying what the rules actually
*are*, other than "If it starts with a digit, then its treated as a
number, otherwise it is used as a string".

So we know the key is a string (it does not start with a digit); the
next question: which string?

The PEP says, as an implementation note, "The str.format() function
will have a minimalist parser which only attempts to figure out when it
is "done" with an identifier (by finding a '.' or a ']', or '}', etc.)."

This probably means to say that it looks for ']' in this context (a
getitem operator), so then the string would be "{foo}{bar}". I would
expect that this produces

KeyError: '{foo}{bar}'

I.e. according to the PEP

a) nested curly braces are not supported in compound field names (*),
   the only valid operators are '.' and '[]'.
b) concatenation of strings in keys is not supported (again because
   the only operators are getattr and getitem)

I now agree with Bill that we have a "computation of matching braces
problem", surprisingly: people disagree with each other and with the
PEP what the meaning of the braces in above example is.

Regards,
Martin

(*) they are supported in format specifiers


More information about the Python-3000 mailing list