Could this potentially be helpful with this example?
```python
class A(object):
value: int
some: object
# Case 1:
if isinstance(some, A) and some.value > 0:
reveal_type(some) # Revealed type is 'ex.A'
# Case 2:
is_correct_a = (
isinstance(some, A) and
some.value > 0
)
if is_correct_a:
reveal_type(some) # Revealed type is 'builtins.object'
```
- Case 1 works perfectly already
- Case 2 does not :(
вс, 4 окт. 2020 г. в 16:45, Sebastian Rittau
I occasionally receive questions from pyright users about extending type narrowing to handle cases that are not possible with today’s Python type system.
Typescript provides a useful facility called [user-defined type guards]( https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-define...)
Am 30.09.20 um 23:40 schrieb Eric Traut: that allows users to extend the notion of type narrowing. It would be straightforward to add this idea to Python. Do others think this would be useful, and is there any interest in standardizing this?
In typescript I find user-defined type guards to be quite helpful and there have been a few occasions where I wished to have them in Python. Unfortunately I don't remember the situations exactly. But parsing JSON is one example where it can be useful:
``` class SomeShape(TypedDict): ...
def has_some_shape(j: object) -> TypeGuard[SomeShape]: ...
def do_stuff(shape: SomeShape) -> None: ...
j = json.loads(...) if has_some_shape(j): do_stuff(j) elif has_some_other_shape(j): do_other_stuff(j) else: raise ValueError(...) ```
do_stuff() and do_other_stuff() can be safely typed then.
Here’s a concrete proposal. We could add a new generic type called `TypeGuard` in the `typing` module. It would be a subclass of bool, defined simply as:
def is_two_element_tuple(val: Tuple[_T, ...]) -> TypeGuard[Tuple[_T, _T]]: return TypeGuard(len(val) == 2)
Why is wrapping the response in TypeGuard() necessary? Couldn't we just do the following in a TypeGuard-aware type checker?
def is_two_element_tuple(val: Tuple[_T, ...]) -> TypeGuard[Tuple[_T, _T]]: return len(val) == 2
- Sebastian _______________________________________________ Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org https://mail.python.org/mailman3/lists/typing-sig.python.org/ Member address: n.a.sobolev@gmail.com