Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Typing & static analysisMiddleCommonPractical

What is type narrowing, and how does an `isinstance()` check enable it for a static type checker?

Answer

Type narrowing is when a type checker refines a variable's known type within a particular branch of code, based on a runtime check the code performs, without you needing to add any extra type annotation. Inside `if isinstance(value, str):`, a checker treats `value` as definitely `str` for the rest of that branch even if its declared type was a broader union like `str | int`, letting you call `.upper()` safely inside the branch while the checker still flags `.upper()` outside it, since `value` could still be an `int` there.

Strong answer includes

  • checker refines a variable's known type within a branch based on a runtime check
  • isinstance is the most common narrowing check, no extra annotation needed
  • narrowing only applies inside the branch where the check held

Practical example

Python example
def describe(value: str | int) -> str:
    if isinstance(value, str):
        return value.upper()
    return str(value * 2)

type-checks cleanly because each branch narrows `value` to exactly the type it uses.

#typing#isinstance

Sources

typing — Support for type hintsPython Software Foundation · Generics, protocols, overloads and typing-module semantics