[issue44683] String formatting

Dennis Sweeney report at bugs.python.org
Tue Jul 20 11:59:56 EDT 2021


Dennis Sweeney <sweeney.dennis650 at gmail.com> added the comment:

If I understand correctly, this shows the behavior you're objecting to:

>>> class A:
...     def __getitem__(self, key):
...         print(f"{key = }")
...         return "apple"
... 
...     
>>> '{0[1]}'.format(A()) # passes an integer
key = 1
'apple'
>>> '{0[apple]}'.format(A()) # passes a string
key = 'apple'
'apple'
>>> '{0["1"]}'.format(A()) # passes the length-3 string including double-quotes
key = '"1"'
'apple'

There's no clear way to use str.format() to get the value for the string key "1". However, I don't think it makes sense to backwards-incompatibly change the behavior to pass the string "1" instead of the integer 1, since a common use is indexing with integers like

    >>> "{0[0]}{0[2]}{0[4]}".format(("a", "b", "c, "d", "e"))
    'ace'

This is an edge case, but it is aligned with the specification: according to https://docs.python.org/3/library/string.html#format-string-syntax,

    """Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string."""

----------
nosy: +Dennis Sweeney

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44683>
_______________________________________


More information about the Python-bugs-list mailing list