[Python-Dev] The syntax of replacement fields in format strings

Serhiy Storchaka storchaka at gmail.com
Tue Oct 31 06:37:27 EDT 2017

According to the specification of format string syntax [1] (I meant 
str.format(), not f-strings), both argument name and attribute name must 
be Python identifiers.

But the current implementation is more lenient and allow arbitrary 
sequences of characters while they don't contain '.', '[', ']', '{', 
'}', ':', '!'.

 >>> '{#}'.format_map({'#': 42})
 >>> import types
 >>> '{0.#}'.format(types.SimpleNamespace(**{'#': 42}))

This can be confusing due to similarity with the format string syntaxes 
in str.format() and f-strings.

 >> name = 'abc'
 >>> f'{name.upper()}'
 >>> '{name.upper()}'.format(name='abc')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'upper()'

If accept only identifiers, we could produce more specific error message.

Is there a bug in the documentation or in the implementation?

[1] https://docs.python.org/3/library/string.html#format-string-syntax

More information about the Python-Dev mailing list