[New-bugs-announce] [issue7972] Have sequence multiplication call int() or return NotImplemented so that it can be overridden with __rmul__

Aaron Meurer report at bugs.python.org
Sat Feb 20 21:36:58 CET 2010


New submission from Aaron Meurer <asmeurer at gmail.com>:

This works in Python 2.5 but not in Python 2.6.

If you do [0]*5, it gives you [0, 0, 0, 0, 0].  I tried getting this to work with SymPy's Integer class, so that [0]*Integer(5) would return the same, but unfortunately, the sequence multiplication doesn't seem to return NotImplemented properly allowing it to be overridden in __rmul__.  Overridding in regular __mul__ of course works fine.  From sympy/core/basic.py (modified):

    # This works fine
    @_sympifyit('other', NotImplemented)
    def __mul__(self, other):
        if type(other) in (tuple, list) and self.is_Integer:
            return int(self)*other
        return Mul(self, other)
    # This has no affect.
    @_sympifyit('other', NotImplemented)
    def __rmul__(self, other):
        if type(other) in (tuple, list, str) and self.is_Integer:
            return other*int(self)
        return Mul(other, self)

In other words, with the above, Integer(5)*[0] works, but [0]*Integer(5) raises TypeError: can't multiply sequence by non-int of type 'Integer' just as it does without any changes.  See also my branch at github with these changes http://github.com/asmeurer/sympy/tree/list-int-mul.

Another option might be to just have the list.__mul__(self, other) try calling int(other).  

SymPy has not yet been ported to Python 3, so I am sorry that I cannot test if it works there.

----------
messages: 99629
nosy: Aaron.Meurer
severity: normal
status: open
title: Have sequence multiplication call int() or return NotImplemented so that it can be overridden with __rmul__
type: behavior
versions: Python 2.6

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


More information about the New-bugs-announce mailing list