Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OverflowError: Python int too large to convert to C long

Tags:

python

I have this class:

class MetricInt(int):
    """Int wrapper that adds only during the observation window."""
    def __new__(cls, _, initial):
        return int.__new__(cls, initial)

    def __init__(self, sim, initial):
        int.__init__(initial)
        self.sim = sim

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

Which basically overwrite the __add__ method in order to only to the addition if self.sim.in_observe_window() returns True.

However, if the initial value is too big, I have :

OverflowError: Python int too large to convert to C long.

What is the correct way to do what I'm trying to do and also handle big numbers?

like image 738
Maxime Chéramy Avatar asked Oct 29 '13 23:10

Maxime Chéramy


1 Answers

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

like image 91
Eevee Avatar answered Nov 09 '22 16:11

Eevee