python / python/mypy

Explicit Any check for TypeGuard

Open
#12,049 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-disallow-any topic-typeguard-typeis
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Explicit Any check does not examine the type argument of a typeguard. An example is,

def foo(x: object) -> TypeGuard[Any]:
  ...

when run with mypy --disallow-explicit-any raises no error.

Expected Behavior

I would expect 1 type error on the function definition line.

Your Environment

Using master mypy.

I'm debugging this as the issue was brought up in this pr, that TypeGuardType currently does not implement accept. If it did check TypeGuard type for explicit Any it would end up crashing. So there's two fixes needed here, 1. Check typeguard argument, and 2. Add an accept.

The function signature is checked for Any, but it happens after normalization of typeguard to bool. By the time the Any check occurs on this line while the function signature looks like this,

def (_mypy_marker: Union[builtins.int, builtins.str]) -> TypeGuard[Any]

but if you check ret_type of typ object it shows bool.

My guess is a fix could be done around here, https://github.com/python/mypy/blob/619d9bdf7ae70ce953f1a10aebccfdc3526b7200/mypy/typeanal.py#L591 when typeguard argument get analyzed. Alternatively normalization to bool could be avoided, but removing normalization is probably a bigger change.

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 in mypy/typeanal.py around the TypeGuard analysis near the referenced lines, and inspect how TypeGuardType is normalized and whether it implements accept. Reproduce the example with --disallow-explicit-any; done means TypeGuard[Any] produces one type error on the function definition without crashing during analysis.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.