Skip to content

TypeGuard behavior does not match python semantics in async functions #19608

@BobTheBuidler

Description

@BobTheBuidler

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions