4 ms·
There is a numbers.Number for that - but yeah, that's another way in which it's just not a good example.. I think typing_extensions.Protocol helps support the
by hannibalhorn 6y ago
There is a numbers.Number for that - but yeah, that's another way in which it's just not a good example..
I think typing_extensions.Protocol helps support the general duck typing "any object that has method x", though there are some implementation issues w/ dataclasses and such..
- pansa2 6y ago> There is a numbers.Number for that That won't help if I want to square a matrix, or a polynomial. > typing_extensions.Protocol helps support the general duck typing "any object that has method x" Even if there's a `powerable` protocol that could be used to annotate `square` and `cube`, how would you annotate a slightly more complex function like `poly`? def square(x): return x**2 def cube(x): return x**3 def poly(x): return 3 * x**2 + 2 * x
- TylerE 6y agoIt wouldn’t be a “squareable” What’s you want is something like “commutative multiplication”
- thomasahle 6y agoWhile duck typing solves this problem on paper, how is a user to find out whether square really accepts a matrix? From comments? They are again limited by the authors imagination. From reading the source?
- anilakar 6y agoUsing maths to either oppose or support generic duck typing is just pointless, because it's easy to come up with counterexamples where a mathematical operation would or would not behave as expected. In quite a few cases where one would overload a mathematical operation to, say, sum two objects of certain type, it'd be better to explicitly type out the operation as a functor/lambda.
- pansa2 6y agoYes, read the comments or the source code. Or the documentation. Or `help(square)`. Or just try `square(Matrix([1, 2], [3, 4]))` in the REPL. How would you use type annotations to show that `square` accepts a matrix (as well as an int, float, rational number etc.)?
- feanaro 6y ago> How would you use type annotations to show that `square` accepts a matrix (as well as an int, float, rational number etc.)? Semi-seriously: by specifying the input type is a Monoid.
- dragonwriter 6y ago> how is a user to find out whether square really accepts a matrix? How do you find out that a function exists, what it accepts, and what it does normally? > From comments? They are again limited by the authors imagination. Sure, but an author which much experience with duck typing will typically write documentation that specified that expected methods (informal structural “types”) rather than nominal types. With the static equivalent (protocols), it’s conceivable that this is also discoverable via tooling.
- jononor 6y agoMaybe something like `numpy.typing.ArrayLike|numbers.Number`. Not incredibly precise. But if this covers also pandas.Series (not entirely sure), then I think it would cover 99.9% of my practical needs. numpy arrays are effectively the standard library datatype for matrices in Python land.