Skip to content

Any Narrowing Question #2444

Answered by erictraut
GBeauregard asked this question in Q&A
Oct 16, 2021 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

This type evaluation result is a natural application of the normal rules for "or" and "and" expressions and isinstance type narrowing.

In general, Any is never narrowed (or widened), but there are three important exceptions to this rule: isinstance, issubclass, and a user-defined type guard function. These three cases are allowed to narrow Any.

Consider this example.

def analyze(obj: Any):
    if isinstance(obj, int) or isinstance(obj, str):
        reveal_type(obj)

I think you'd agree that the revealed type should be int | str in this case.

Now, let's replace the first isinstance call with a call to some other random function that doesn't imply any type narrowing.

def analyze(obj: Any):
…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@GBeauregard
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
2 participants