How to create a type that is closed under inherited operations?
Clash Royale CLAN TAG #URR8PPP up vote 6 down vote favorite 2 In the mathematical sense, a set (or type) is closed under an operation if the operation always returns a member of the set itself. This question is about making a class that is closed under all operations inherited from its superclasses. Consider the following class. class MyInt(int): pass Since __add__ has not been overridden, it is not closed under addition. x = MyInt(6) print(type(x + x)) # <class 'int'> One very tedious way to make the type closed would be to manually cast back the result of every operation that returns an int to MyInt . Here, I automated that process using a metaclass, but this seems like an overly complex solution. import functools class ClosedMeta(type): _register = def __new__(cls, name, bases, namespace): # A unique id for the class uid = max(cls._register) + 1 if cls._register else 0 def tail_cast(f): @functools.wraps(f) def wrapper(*args, **kwargs): out = f(*...