python / python/mypy

TypeGuard behavior does not match python semantics in async functions

Open
#19,608 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I'm not sure if this should go here or in the mypyc issue tracker. I believe its a bug in mypy itself which only causes notable issues when you compile code with mypyc.

Bug Report

TypeGuard behavior does not match python semantics in async functions. The block which a TypeGuard applies to should end at the next await, assuming the TypeGuard is on an instance attribute or some other mutable nonlocal var.

This causes unnecessary TypeErrors in mypyc-compiled code.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=50cf9499e4e5be34d3faa754bd6052c0

Note: This code snippet does not produce any mypy errors, the bug is only exposed when compiling similar code with mypyc.

Expected Behavior

The TypeGuard should only guarantee the type of self._db up to the next await/async with/async for, because after that point the type is no longer guaranteed.

Actual Behavior

The TypeGuard "guarantees" the type of self._db longer than it is logically able to. Mypyc will raise a TypeError on line 12 if another task sets self._db while our coroutine waits for the lock.

Your Environment

  • Mypy version used: 1.17.0
  • Python version used: 3.12

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 with the linked mypy-play reproducer and compare TypeGuard narrowing before and after await, async with, and async for. Trace the relevant async-function type-checking behavior and add regression coverage showing that a mutable nonlocal value is not narrowed beyond the suspension point; done means mypyc no longer encounters the reported TypeError.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.