Could this potentially be helpful with this example?

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 <>:
Am 30.09.20 um 23:40 schrieb Eric Traut:
> 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]( 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):
elif has_some_other_shape(j):
     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 --
To unsubscribe send an email to
Member address: