Why doesn't __rmod__ work properly for strings? [duplicate]

大城市里の小女人 提交于 2019-12-25 18:12:33

问题


>>> 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:


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+.



来源:https://stackoverflow.com/questions/46854740/why-doesnt-rmod-work-properly-for-strings

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