Skip to content

Instantly share code, notes, and snippets.

@ramalho
Created June 17, 2020 02:25
Show Gist options
  • Save ramalho/9f67fd245f424939c73e5c3bb21fa949 to your computer and use it in GitHub Desktop.
Save ramalho/9f67fd245f424939c73e5c3bb21fa949 to your computer and use it in GitHub Desktop.
Strange number protocols
builtins numpy builtins numpy decimal fractions builtins numpy
complex complex64 float float16 Decimal Fraction int uint8
----------------------------------------------------------------------------------------------
numbers.Number • • • • • • • •
----------------------------------------------------------------------------------------------
numbers.Complex • • • • • • •
SupportsComplex • • •
complex(x) (1+0j) (1+0j) (1+0j) (1+0j) (1+0j) (1+0j) (1+0j) (1+0j)
----------------------------------------------------------------------------------------------
numbers.Real • • • • •
SupportsFloat • • • • • • • •
float(x) 1.0 1.0 1.0 1.0 1.0 1.0 1.0
----------------------------------------------------------------------------------------------
numbers.Rational • • •
----------------------------------------------------------------------------------------------
numbers.Integral • •
SupportsInt • • • • • • •
int(x) 1 1 1 1 1 1 1
----------------------------------------------------------------------------------------------
SupportsIndex • •
operator.index(x) 1 1
----------------------------------------------------------------------------------------------
SupportsRound • • • • • • •
round(x) (1+0j) 1 1.0 1 1 1 1
from decimal import Decimal
from fractions import Fraction
from numbers import *
import typing
import numpy as np
import operator
np_number = np.number
num_types = [
complex, np.complex64, float, np.float16, Decimal, Fraction, int,
np.uint8]
test_fn = [complex, float, int, operator.index, round]
protocols = [
typing.SupportsComplex, typing.SupportsFloat,
typing.SupportsInt, typing.SupportsIndex, typing.SupportsRound]
print(' ' * 16, end='')
for t in num_types:
print(f'{t.__module__:^10}', end='')
print()
print(' ' * 16, end='')
for t in num_types:
print(f'{t.__name__:^10}', end='')
print()
abcs = [Number, Complex, Real, Rational, Integral]
for cls in abcs+protocols:
print(f'{cls.__name__:16}', end='')
for t in num_types:
c = '*' if issubclass(t, cls) else ' '
print(f'{c:^10}', end='')
print()
for fn in test_fn:
print(f'{fn.__name__:16}', end='')
for t in num_types:
instance = t(1)
try:
res = fn(instance)
except TypeError:
result = ' '
else:
result = repr(res)
print(f'{result:^10}', end='')
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment