Type operators in Python
Hi ! I'm currently thinking on ways to improved numpy numerical stack typing (dtype mostly), when it comes to mixing the types. For example if you add an int32 to a float64, you'll get a float64.
There is a quick and dirty way to deal with all this: use overloading, but I won't see it scaling at all (think pytorch / tensorflow that are using numpy dtypes and defining a ton of new functions). Also if we want to abstract over these dtype, for example with something like
def my_add(x : dtype0, y: dtype1) > ???:
In this case, overloading won't help. So I was thining of maybe adding a type operator, something like
def my_add(x: dtype0, y:dtype1) > typing.numpy.join(dtype0, dtype1):
I'm not sure that the right approach too, but since I'm new to python typing, I wondered if such "type" operators already existed in the wild ?
Best, Vincent
Hi Vincent,
If you want to consider int32 a subtype of float64 (e.g. using type promotion mechanism used by mypy for Python int and float), then you can just use a type variable:
def my_add(x: T, y: T) > T: ...
You can make it constrained to accept only some types `T = TypeVar('T', int32, float64)`. If you however don't want to use type promotions (since it is technically unsafe and exist for practicality beats purity purposes) then you don't have options currently since type expressions/operators are not supported. One can of course write a plugin for mypy, but then it will only work with mypy, not with other type checkers.
 Ivan
On Tue, 30 Apr 2019 at 05:23, Vincent Siles vincent.siles+pyty@gmail.com wrote:
Hi ! I'm currently thinking on ways to improved numpy numerical stack typing (dtype mostly), when it comes to mixing the types. For example if you add an int32 to a float64, you'll get a float64.
There is a quick and dirty way to deal with all this: use overloading, but I won't see it scaling at all (think pytorch / tensorflow that are using numpy dtypes and defining a ton of new functions). Also if we want to abstract over these dtype, for example with something like
def my_add(x : dtype0, y: dtype1) > ???:
In this case, overloading won't help. So I was thining of maybe adding a type operator, something like
def my_add(x: dtype0, y:dtype1) > typing.numpy.join(dtype0, dtype1):
I'm not sure that the right approach too, but since I'm new to python typing, I wondered if such "type" operators already existed in the wild ?
Best, Vincent _______________________________________________ Typingsig mailing list  typingsig@python.org To unsubscribe send an email to typingsigleave@python.org https://mail.python.org/mailman3/lists/typingsig.python.org/
participants (2)

Ivan Levkivskyi

Vincent Siles