How to type hint a generic numeric type in Python?

Francesco Boi picture Francesco Boi · Mar 10, 2020 · Viewed 11.8k times · Source

Forgive me if this question has been asked before but I could not find any related answer.

Consider a function that takes a numerical type as input parameter:

def foo(a):
    return ((a+1)*2)**4;

This works with integers, floats and complex numbers.

Is there a basic type so that I can do a type hinting (of a real existing type/base class), such as:

def foo(a: numeric):
    return ((a+1)*2)**4;

Furthermore I need to use this in a collection type parameter, such as:

from typing import Collection;
def foo(_in: Collection[numeric]):
    return ((_in[0]+_in[1])*2)**4;

Answer

juanpa.arrivillaga picture juanpa.arrivillaga · Mar 10, 2020

PEP 3141 added abstract base classes for numbers, so you could use:

from numbers import Number

def foo(a: Number) -> Number:
    ...