0

I am trying to subclass pandas' Timedelta so when it gets summed by a integer/float, we consider it as a Timedelta with seconds.

I tried the following:

class Timedelta(pd.Timedelta):
    def __add__(self, other):
        print("OVERRIDEN ADD")
        try:
            print("SUPER ADD")
            return super().__add__(other)
        except:
            print("NEW ADD")
            return super().__add__(Timedelta(str(other)+"s"))

But for some reason I can't get it to go to the "NEW ADD" implementation:

>>> a = Timedelta2('10s')
>>> a+1
OVERRIDEN ADD
Traceback (most recent call last):
  File "C:\Python36\lib\site-packages\IPython\core\interactiveshell.py", line 2910, in run_code
SUPER ADD
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-51-98b939904c8e>", line 1, in <module>
    a+1
TypeError: unsupported operand type(s) for +: 'Timedelta2' and 'int'

I was expecting this TypeError exception to be caught, but for some reason it isn't, so I would like to ask for some help to figure out what could be happening here.

Thanks!

SuperGeo
  • 763
  • 7
  • 22

2 Answers2

4

super().__add__(other) doesn't raise an exception! It returns NotImplemented. That's how you signal that your operator overload doesn't understand the argument it's getting. The TypeError comes from the operator machinery once both sides say they can't perform the operation.

Instead of trying to catch an exception that isn't coming from there anyway, check whether super().__add__(other) returns NotImplemented.

user2357112
  • 260,549
  • 28
  • 431
  • 505
1

You are no really understand the __add__ method! try below way to got your expect! try ... expect is not efficient, so you should use if .. else instead.

import pandas as pd

class MyTimedelta(pd.Timedelta):
    def __add__(self, other):
        print("OVERRIDEN ADD")
        if isinstance(other, int):
            return pd.Timedelta("{}s".format(int(self.seconds)+ other))
        else:    
            super(MyTimedelta, self).__add__(other)

and then you can do the operation like:

In [22]: s=MyTimedelta('2s')

In [23]: s+3
OVERRIDEN ADD
Out[23]: Timedelta('0 days 00:00:05')
Frank AK
  • 1,705
  • 15
  • 28
  • What do you mean `try ... except` is not efficient? It is much more efficient than checking the value's type every single time. Try [this](https://pastebin.com/Am0HLcpu). – Jose A. García Jan 26 '18 at 09:52
  • Relevant question: [Python FAQ: “How fast are exceptions?”](https://stackoverflow.com/q/8107695/216074) – poke Jan 26 '18 at 20:19