Thursday 30 September 2021

How to hint at number *types* (i.e. subclasses of Number) - not numbers themselves?

Assuming I want to write a function that accepts any type of number in Python, I can annotate it as follows:

from numbers import Number

def foo(bar: Number):
    print(bar)

Taking this concept one step further, I am writing functions which accept number types, i.e. int, float or numpy dtypes, as arguments. Currently, I am writing:

from typing import Type

def foo(bar: Type):
    assert issubclass(bar, Number)
    print(bar)

I thought I could substitute Type with something like NumberType (similar to NotImplementedType and friends, re-introduced in Python 3.10), because all number types are subclasses of Number:

from numbers import Number
import numpy as np

assert issubclass(int, Number)
assert issubclass(np.uint8, Number)

As it turns out (or at least as far as I can tell), there is no such thing as a generic NumberType in Python (3.9):

>>> type(Number)
abc.ABCMeta

Is there a clean way (i.e. without runtime checks) to achieve the desired kind of annotation?



from How to hint at number *types* (i.e. subclasses of Number) - not numbers themselves?

No comments:

Post a Comment