This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Have sequence multiplication call int() or return NotImplemented so that it can be overridden with __rmul__
Type: behavior Stage:
Components: Versions: Python 2.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Aaron.Meurer
Priority: normal Keywords:

Created on 2010-02-20 20:36 by Aaron.Meurer, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg99629 - (view) Author: Aaron Meurer (Aaron.Meurer) Date: 2010-02-20 20:36
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.
msg99632 - (view) Author: Aaron Meurer (Aaron.Meurer) Date: 2010-02-20 20:51
This seems to work after all.  Could someone mark this as invalid?
History
Date User Action Args
2022-04-11 14:56:57adminsetgithub: 52220
2010-02-20 20:53:00benjamin.petersonsetstatus: open -> closed
resolution: not a bug
2010-02-20 20:51:37Aaron.Meurersetmessages: + msg99632
2010-02-20 20:36:57Aaron.Meurercreate