[New-bugs-announce] [issue28598] RHS not consulted in `str % subclass_of_str` case.

Martijn Pieters report at bugs.python.org
Thu Nov 3 09:36:04 EDT 2016


New submission from Martijn Pieters:

The `BINARY_MODULO` operator hardcodes a test for `PyUnicode`:

        TARGET(BINARY_MODULO) {
            PyObject *divisor = POP();
            PyObject *dividend = TOP();
            PyObject *res = PyUnicode_CheckExact(dividend) ?
                PyUnicode_Format(dividend, divisor) :
                PyNumber_Remainder(dividend, divisor);

This means that a RHS subclass of str can't override the operator:

>>> class Foo(str):
...     def __rmod__(self, other):
...         return self % other
...
>>> "Bar: %s" % Foo("Foo: %s")
'Bar: Foo %s'

The expected output there is "Foo: Bar %s".

This works correctly for `bytes`:

>>> class FooBytes(bytes):
...     def __rmod__(self, other):
...         return self % other
...
>>> b"Bar: %s" % FooBytes(b"Foo: %s")
b'Foo: Bar: %s'

and for all other types where the RHS is a subclass.

Perhaps there should be a test to see if `divisor` is a subclass, and in that case take the slow path?

----------
components: Interpreter Core
messages: 279993
nosy: mjpieters
priority: normal
severity: normal
status: open
title: RHS not consulted in `str % subclass_of_str` case.
type: behavior
versions: Python 2.7, Python 3.3, Python 3.4, Python 3.5, Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue28598>
_______________________________________


More information about the New-bugs-announce mailing list