I would like to write a generic function that takes an instance of any type that implements all real number operations (such as int
, float
, fractions.Fraction
, or third-party types). I found the numbers.Real
ABC which works great for enforcing the type at runtime with a isinstance(x, numbers.Real)
check, and all built-in real number numeric types in Python are registered as a virtual subclass of it.
But I found out the hard way that while it works great for run-time checks, it doesn’t work well for type annotation purposes because all major type checkers ignore usages of abc.ABC.register
. So how do I annotate my parameters which accepts any real numeric type then?
This post in a discussion suggests using the typing.SupportsInt
protocol in favor of the numbers.Integral
ABC, but in my case I need a replacement for numbers.Real
. Also, it only checks if a class implements __int__
, not if it supports all integral operations. And something like typing.SupportsReal
doesn’t exist… Would I just have to define my own protocol that checks for the existence of all real number operation dunder methods (__add__
, __sub__
, __mul__
, __div__
, __truediv__
, etc…)?