top | item 34419734

(no title)

Slippery_John | 3 years ago

Python's type hints are definitely an improvement and they're getting better all the time, but they're still frustrating to use at anything approaching the edge. I long for something as elegant and functional as TypeScript.

One hurdle I've stumbled over recently is the question "what is a type?", the answer can be surprising. Unions, for example, are types but not `Type`s. A function that takes an argument of type `Type` will not accept a Union. So if you want to write a function that effectively "casts" a parameter to a specified type, you can't. The best you can do is have an overload that accepts `Type` and does an actual cast, and then another that just turns it into `Any`. This is, in fact, how the standard library types its `cast` function [1]. The argument I've seen for the current behavior is that `Type` describes anything that can be passed to isinstance, but that's not a satisfying answer. Even then, `Union` can be passed to isinstance and still does not work with `Type`. Talk currently is to introduce a new kind of type called `TypeForm` or something to address this, which is certainly an improvement over nothing, but still feels like technical debt.

[1]: https://github.com/python/typeshed/blob/main/stdlib/typing.p...

discuss

order

No comments yet.