Typing Number, PyCharm

dn PythonList at DancesWithMice.info
Sat Feb 4 21:30:18 EST 2023


Do we have a typing type-hint for numbers yet?


Often wanting to combine int and float, discovered that an application 
was doing a walk-through with/for uses three numeric types. Was 
intrigued to note variance, in that the code-set features two different 
methods for typing, in this situation:

def func( value ):
     ...using value...

where value may be an integer, a floating-point value, or a 
complex-number (but not decimal-type).
NB code snippets from memory (cf copy-paste)


Method 1 (possibly older code):-

from typing import Union
...
def fun( value:Union[ int, float, complex ] ):


Method 2:-

def fun( value:int|float|complex  ):


Pondering this, realised could use an alias to de-clutter the 
function-definition/signature:

Method 3:-

number_type = int|float|complex
...
def fun( value:number_type  ):


If it was important to have type consistency within the union, eg 
argument and return, could go for:

Method 4:-

from typing import TypeVar
number_type = TypeVar( 'number_type', int, float, complex )
...
def fun( value:number_type  ):


Then remembered the way we'd code an execution-time check for this using 
isinstance():

Method 5:-

from numbers import Number
...
def fun( value:Number  ):


Each of these will execute correctly.

All cause PyCharm to object if I try to call the fun(ction) with a 
string parameter - and execute an exception, as expected.


Accepting all the others, am curious as to why PyCharm objects to Method 
5 with "Expected type 'SupportsFloat | SupportsComplex | complex | 
SupportsIndex', got 'Number' instead? - yet still highlights the 
erroneous string parameter but none of the 'legal' data-types?

As soon as a list (in this case types) reaches three, my aged-eyes start 
to think de-cluttering is a good idea!

Do you know of another way to attack this/more properly?

-- 
Regards,
=dn


More information about the Python-list mailing list