[issue45704] string.Formatter.parse does not handle auto-numbered positional fields

Sascha Desch report at bugs.python.org
Fri Nov 5 09:31:48 EDT 2021


Sascha Desch <sascha.desch at hotmail.com> added the comment:

That definition of `.parse()` definitely makes sense. Do you then think this is out of scope for `Formatter` in general or just for `.parse()`?. Just for reference, this is what I currently use to get automatic numbering to work for my use case. 

```
def parse_command_template(format_string):

    auto_numbering_error = ValueError(
        'cannot switch from automatic field numbering to manual field specification')

    index = 0
    auto_numbering = None

    for literal_text, field_name, spec, conversion in Formatter().parse(format_string):
        if field_name is not None:
            if field_name.isdigit():
                if auto_numbering is True:
                    raise auto_numbering_error
                auto_numbering = False

            if field_name == '':
                if auto_numbering is False:
                    raise auto_numbering_error
                auto_numbering = True
                field_name = str(index)
                index += 1

        yield literal_text, field_name, spec, conversion
```

----------

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


More information about the Python-bugs-list mailing list