How to extend built in `Decimal` class?

I would like to have a class which is exactly like the Decimal class, but which has a custom __format__ method. The important thing is that if I take two NewDecimal objects and add them, or multiply, exponentiate etc. it should return a new NewDecimal object. This can be accomplished by overwriting various methods like __add__, __radd__, __pow__ etc. My questions:

  • How do I setup the new class so that it gets created (__new__) and instanstiated (__init__) correctly
  • Is there a better way to get all of the mathematical operations to work properly other than manually overriding all the relevant methods?
  • If the answer to the previous question is “no” then how do I know what the complete list of methods I need to overwrite is? Where can I find such a list?

Recently, there was this post. You could use what they did there.

I don’t know if complete, but those that return Decimal among them methods in Decimal.__dict__ you can give them the treatment in the link.

1 Like

Thanks for the ref.

  • You don’t need to change anything to __new__ and __init__, except if you want to add features at that time (to change the constructor signature, that’s usually the starting point of such an edit).
  • No, there is not at the moment. That’s the purpose of my proposition in Ideas. Though you may use the code I prototyped there, the one on Colab.
  • Cross the list of operation methods at datamo with those Decimal is supposed to implement (for example, __matmul__ is not implemented). Among those, check which are supposed to / you want to return an instance of the same class (for example, __index__ and __len__ are not but __mul__ and __neg__ probably are).

Wow, shockingly timely, thank you!

For the Decimal class I’m afraid I’ll also need to overwrite methods like from_float(), normalize, etc. Though, with the linked automated approach, it seems like this shouldn’t be too bad as long as the functions I need to replace have on Decimal return value.