python / python/mypy

Type inference into function

Open
#14,236 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Feature

I tried to search using some keywords and couldn't find anything obvious. But I was trying to do type validation of a class that I don't control (external sdk) and it has a class with optional fields. I'd like to write a function to validate that the instance I am passed as the correct field types, instead of doing it all in one.

Pitch

Ability to do type validation of objects you don't have control of in a subfunction, instead of in a main function.

import typing as t


class Test:
    opt: t.Optional[str]


def validate_test(t: Test) -> None:
    assert (t.opt)


def check_test_not_working() -> None:
    t = Test()
    validate_test(t)
    # Expect str, get Union[str, None]
    reveal_type(t.opt)


def check_test_working() -> None:
    t = Test()
    assert (t.opt)
    # Expect str, get str
    reveal_type(t.opt)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the issue with the shown Test, validate_test, and reveal_type examples, then inspect how mypy propagates narrowing across function calls. Done means a supported approach lets the helper's assertion narrow t.opt at the caller while preserving existing Optional behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.