Why doesn't __rmod__ work properly for strings

2019-09-21 00:42发布

This question already has an answer here:

>>> class MyInt(int):
...     def __rmod__(self, other):
...         return 42
...     
>>> class MyStr(str):
...     def __rmod__(self, other):
...         return 'wat'
...     
>>> 0 % MyInt()
42
>>> '%r' % MyStr()
"''"

Why is the int subclass able to control this BinOp from the reflected side, but str can not? This seems to contradict the documented datamodel.

I was hoping to use the feature to create a non-intrusive and backwards-compatible extension providing curly-braces-style handlers/formatters for the logging framework, but this stopped me in my tracks. Is that a bug?

Python 3.6.0 on Linux. Using collections.UserString as a base class also has the issue. Using bytes as a base does not.

1条回答
仙女界的扛把子
2楼-- · 2019-09-21 01:18

This is Python issue 28598. The fast path for % string formatting in the bytecode evaluation loop wasn't checking for string subclasses. It's fixed now, so update your Python to v3.6.1+.

查看更多
登录 后发表回答