On 12/22/20 4:27 PM, Guido van Rossum wrote:
Another Sebastian (Rittau) asked about "type assertions" which raise an exception instead of returning False. I wonder if that couldn't be handled by writing an explicit assert statement, e.g. ``` def f(x: Tuple[str, ...]): assert is_two_element_tuple(x) # Now x has type Tuple[T, T] ```
I like the use of combining assert with a TypeGuard-returning function. Makes a lot of sense to me. On 12/22/20 6:55 PM, Shantanu Jain wrote:
If we got around to adding a safe_cast a la https://github.com/python/mypy/issues/5687, this would also allow the user to explicitly opt in to strict or non strict type narrowing.
I meant https://github.com/python/mypy/issues/5756 although the issue I linked is related.
Tangent: I might point out it's possible to trivially implement safe_cast() in pure Python if you use TypeForm (from a different PEP I'm working on at [1]): ``` def safe_cast(form: TypeForm[T], value: T) -> T: return value ``` [1]: https://github.com/python/mypy/issues/9773 It's also possible to implement cast() in pure Python with TypeGuard and TypeForm combined: ``` def cast(form: TypeForm[T], value: object) -> TypeGuard[T]: return value ``` --- David Foster | Seattle, WA, USA Contributor to TypedDict support for mypy