python / cpython

The Python programming language
https://www.python.org/
Other
61.37k stars 29.56k forks source link

argparse: optimizing internal string formatting #107146

Open rodrigogiraoserrao opened 1 year ago

rodrigogiraoserrao commented 1 year ago

Enhancement

Replace non-public facing %-style string formatting in argparse with f-strings.

Pitch

The replacement of %-style formatting with f-strings where possible is a small optimization.

We wouldn't change the public API – so the user still can/still has to use %-style formatting to further customize help/usage messages. Furthermore, we wouldn't change the internal strings that are translated to prevent breaking translation tools elsewhere.

Previous discussion

Informal discussion between me and Lukasz happened at the EuroPython 2023 sprint.

Linked PRs

hpaulj commented 1 year ago

When I first start following argparse issues, it was being used with Python2 as well as 3. It was convenient to have code that could run on both. That's part of why there's not been any rush to replace the old '%' style of formatting.

doraeric commented 3 months ago

I encounter this formatting issue and I believe this issue should be corrected.

If there is a % in help text, it will cause ValueError: unsupported format character and you have to escape this character. Look into the implementation, the error comes from

self._get_help_string(action) % params

which may expand to

help = 'help text with %'
help % params

but I think the user input should be an argument for format string instead of the format string. For example:

'''usage: {}

{}'''.format(prog, help)