你能重载 Python 3.6 f-string 的 "operator" 吗?

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

在 Python 3.6 中,您可以像这样使用 f-strings

>>> date = datetime.date(1991, 10, 12)
>>> f'{date} was on a {date:%A}'
'1991-10-12 was on a Saturday'

我想重载上面接收 '%A' 的方法。可以吗?

例如,如果我想围绕 datetime 编写一个愚蠢的包装器,我可能希望这个重载看起来像:

class MyDatetime:
    def __init__(self, my_datetime, some_other_value):
        self.dt = my_datetime
        self.some_other_value = some_other_value

    def __fstr__(self, format_str):
        return (
            self.dt.strftime(format_str) + 
            'some other string' +
            str(self.some_other_value
        )

,但使用__format__,而不是__fstr__


f-strings 并不是对以前格式化字符串的方法的彻底改造。相反,它建立在已经存在的协议之上。

来自 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.

然后又在 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.

因此,没有 new 适合他们的特殊方法。您需要定义一个 __format__ 方法,该方法接受规范和 returns 一个适当格式化的字符串。

__format__ 上的文档也描述了:

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.