Can you overload the Python 3.6 f-string's “operator”?

放肆的年华 提交于 2019-12-05 01:35:25

Yes, but by using __format__, not __fstr__.


f-strings were not an overhaul of the previous methods to format strings. Instead, it built on the protocols already in place.

From PEP 0498 that introduced them, in Code equivalence:

The exact code used to implement f-strings is not specified. However, it is guaranteed that any embedded value that is converted to a string will use that value's __format__ method. This is the same mechanism that str.format() uses to convert values to strings.

and then again, in Format Specifiers:

Once expressions in a format specifier are evaluated (if necessary), format specifiers are not interpreted by the f-string evaluator. Just as in str.format(), they are merely passed in to the __format__() method of the object being formatted.

So, there's no new special method for them. You need to define a __format__ method that takes the spec and returns an appropriately formatted string.

As the docs on __format__ also describe:

Called by the format() built-in function, and by extension, evaluation of formatted string literals and the str.format() method, to produce a “formatted” string representation of an object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!