How can I make methods of a subclass of Python numeric class return instances of the subclass?

6 days ago 3
ARTICLE AD BOX

You could just not subclass it. Monkey-patching a wrapper will be clunky no matter what you do; you might be better served by using functions with Fraction parameters instead of subclass methods. This has the added benefit of not forcing you to convert Fraction instances to subclass instances every time you call those functions.

Anerdw's user avatar

3 Comments

Of course I can not subclass. I am not talking about monkey-patching, but about subclassing. I was under impression that subclassing was not discouraged in Python. If I have a properly functioning sublclass, I do not need to convert Function instances, I can just use my instances.

2026-03-08T00:09:47.633Z+00:00

@Alexey You are subclassing, but you're also hoping for a way to monkey-patch a conversion to the subclass at the end of every method call.

2026-03-08T00:15:02.887Z+00:00

No, I am not hoping for a way to monkey-patch, I know I can monkey-patch. But I do not want to overload all operators. Please re-read.

2026-03-08T00:27:28.913Z+00:00

Is this the intended behaviour?

Yes, because the implementation of the methods in Lib/fractions.py explicitly return instances of Fraction instead of instances of type(self) (example source for addition).

Is there a way around?

There is, but not from the subclass. The way around would have to be done in Fraction itself, to allow for the possibility of operations on subtypes to return instances of subtypes. This would be done by making the methods return type(self)(...) instead of explicitly returning Fraction. An example of a built-in type which does work like that is datetime:

>>> from datetime import datetime, timedelta >>> class D(datetime): ... pass ... >>> D(2026, 3, 7) D(2026, 3, 7, 0, 0) >>> D(2026, 3, 7) + timedelta(1) # still a D instance, even though `__add__` wasn't overridden D(2026, 3, 8, 0, 0)

wim's user avatar

3 Comments

I could guess that the implementation returns instances of Fraction. IMO this does not yet mean that the behaviour is intended. Is it documented anywhere, with an explanation why sublclassing is not supported?

2026-03-08T00:43:13.347Z+00:00

The current __add__ implementation was from Guido van Rossum himself, you can be 100% sure he's aware of the techniques to account for possibility of returning subtypes from operators (especially since it's done elsewhere in stdlib) and chose not to do it that way.

2026-03-08T00:47:25.347Z+00:00

It's not the sort of detail that would be documented, usually. If there is a convincing use case in mind, you could open a discussion and potentially a pull-request to cpython fractions.py adding support.

2026-03-08T01:17:55.71Z+00:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article