Skip to content

Generic Type Narrowing Consistency/Scope Question #2719

Answered by erictraut
GBeauregard asked this question in Q&A
Discussion options

You must be logged in to vote

When you're using a TypeVar, the type must be consistent throughout the scope. The isinstance check in func is checking to see if x and y are subclasses of A, but that doesn't mean they are type A. They could be a class that is derived from A. For that reason x = A() is not allowed.

In func2, the isinstance check is applying type narrowing to the expression x. A type guard narrows only the type of the expression found within the conditional statement. In this case, that expression is x, so only the type of x is narrowed. If you want to narrow the type of y, you would need to include it in the type guard conditional expression. That's just how type guards work.

In func3, the declared type of

Replies: 1 comment 7 replies

Comment options

You must be logged in to vote
7 replies
@GBeauregard
Comment options

@saaketp
Comment options

@erictraut
Comment options

@GBeauregard
Comment options

@saaketp
Comment options

Answer selected by GBeauregard
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants