classification
Title: str.format and string.Formatter subscript behaviors diverge
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.7, Python 3.6, Python 2.7
process
Status: closed Resolution: duplicate
Dependencies: Superseder: string.Formatter does not support key/attribute access on unnumbered fields
View: 27307
Assigned To: Nosy List: eric.smith, tekknolagi
Priority: normal Keywords: patch

Created on 2020-03-17 01:42 by tekknolagi, last changed 2020-03-19 15:22 by eric.smith. This issue is now closed.

Pull Requests
URL Status Linked Edit
PR 19065 open tekknolagi, 2020-03-19 00:03
Messages (3)
msg364382 - (view) Author: Maxwell Bernstein (tekknolagi) * Date: 2020-03-17 01:42
As I understand it, str.format and string.Formatter are supposed to behave the
same, with string.Formatter being a pluggable variant. While poking at
string.Formatter, I noticed that they do not behave the same when formatting a
nameless subscript:

```
import string
str.format("{[0]}", "hello")  # => "h"
string.Formatter().format("{[0]}", "hello")  # => KeyError("")
```

They seem to work the same in the case where the arg is either indexed by
number or by name:

```
import string
str.format("{0[0]}", "hello")  # => "h"
string.Formatter().format("{0[0]}", "hello")  # => "h"
str.format("{a[0]}", a="hello")  # => "h"
string.Formatter().format("{a[0]}", a="hello")  # => "h"
```

After some digging, I have come up with a couple ideas:

* Change _string.formatter_field_name_split to treat an empty string field name
  as 0, so that string.Formatter.get_value looks up the arg in args, instead of
  kwargs
* Change string.Formatter.get_value to treat empty string key as 0, and look up
  the arg in args, instead of kwargs

I'm happy to submit a PR if people find one of these two solutions palatable or
have some solutions of their own.

(Note: this may appear in other versions, but I don't have them on my machine
to test.)
msg364603 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2020-03-19 14:33
Can you see if the patch in issue27307 solves your problem?
msg364606 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2020-03-19 15:22
In fact, this is a duplicate of issue27307, so I'm going to close this.
History
Date User Action Args
2020-03-19 15:22:33eric.smithsetstatus: open -> closed
superseder: string.Formatter does not support key/attribute access on unnumbered fields
messages: + msg364606

resolution: duplicate
stage: patch review -> resolved
2020-03-19 14:33:52eric.smithsetmessages: + msg364603
2020-03-19 00:03:12tekknolagisetkeywords: + patch
stage: patch review
pull_requests: + pull_request18418
2020-03-17 04:32:22xtreaksetnosy: + eric.smith
2020-03-17 01:42:20tekknolagicreate