OverflowError: Python int too large to convert to C long

I like Eevee's answer about delegating instead. He has not provided any code so I'm doing it:

class MetricInt(object):
    """Int wrapper that adds only during the observation window."""
    def __init__(self, sim, initial):
        self.sim = sim
        self.val = int(initial)

    def __add__(self, val):
        if self.sim.in_observe_window():
            self.val += int(val)
        return self

    def __int__(self):
        return self.val

    def __float__(self):
        return float(self.val)

This way, the problem is solved. When I decided to subclass the int type, it was because I already had a few int variables in my code and did not wanted to change my code too much. However, if I define __int__ and __float__, I only need to add some casts to int. It's not that bad I guess if it avoids weird bugs.


Are you on Python 2.6? You could try subclassing long instead.

But in general I strongly suggest not subclassing Python built-in types; CPython reserves the right to skip calls to special methods on such types, and for example will not call __str__ on a subclass of str. Your example here works, but you might be asking for bugs.

Consider delegating instead, and delegating the operators you want. (You may also want __int__, of course.)

Tags:

Python