Search code examples
pythonpython-3.xstring-formattingsubclassing

Why doesn't __rmod__ work properly for strings?


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


Solution

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