Skip to content

[mypyc] Use __format__ in specialized str.format() and f-strings - #22564

Open
Jahongir-Qurbonov wants to merge 1 commit into
python:masterfrom
Jahongir-Qurbonov:mypyc-fstring-format-subclass
Open

Jahongir-Qurbonov wants to merge 1 commit into
python:masterfrom
Jahongir-Qurbonov:mypyc-fstring-format-subclass

Conversation

@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor

The specialized versions of str.format() and f-strings converted values using str() instead of format(), so __format__ was ignored:

  • An object of a class that defines __format__ was formatted using __str__ in "{}".format(obj) and f"x{obj}y".
  • class E(str, Enum) / IntEnum members are formatted using Enum.__format__, which on Python 3.10 uses the value (f"x{E.A}y" gives "xay", mypyc gave "xE.Ay"). On 3.11+ it's the other way around for a value with static type str: e: str = E.A; f"x{e}y" gives "xE.Ay", mypyc gave "xay".
  • A value with static type str was used as is, even if it was an instance of a str subclass that overrides __format__.

Printf-style formatting ("%s" % x) had the related issue that a value with static type str was used as is, so __str__ of a str subclass wasn't called (e: str = E.A; "%s" % e gave "a" instead of "E.A").

Now str.format() and f-strings use format(x) (PyObject_Format, through a helper with an inline fast path for exact str objects), and % uses str(x) for all values that aren't int. Instances of native classes still use str(x) in str.format() and f-strings if the class and all its subclasses are known and none of them define __format__, since calling object.__format__ is quite a bit slower.

int values still use the existing fast path. An int subclass instance with static type int may not keep its type in compiled code anyway.

The specialized versions of str.format() and f-strings converted values
using str(), which ignored __format__ (for example, of str/int enums or
of str subclasses). Use format() instead. Also use str() for values with
static type str in printf-style formatting, since they may be instances
of str subclasses.

Native classes that don't define __format__ (and whose subclasses don't
define it either) still use str(), which is faster.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant