python / python/mypy

Inconsistent behavior: MyPy rejects isinstance with Any, but accepts cast from Any for ignored imports

オープン
#17,844 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

bug
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Context

When working with the cassandra.cluster module in a Python project, i had to use type: ignore on the import because there are no compatible MyPy stubs available for the module.

Below is a simplified version of how the code is set up.

from cassandra.cluster import Session as CassandraConnection # type: ignore (mypy will treat it just like Any)
from typing import TypeAlias, cast, Any

TransactionalConnection: TypeAlias = CassandraConnection

This approach generally works, but it causes issues with type checking in MyPy.


Initial Problem

When trying to use isinstance() to check if a variable is an instance of TransactionalConnection, Mypy raises the following error:

Cannot use isinstance() with Any type [misc]

This happens because MyPy is treating CassandraConnection as Any due to the #type: ignore. Here's the code that triggers the error:

if isinstance(db_client, TransactionalConnection): pass -> error occurs here: Cannot use isinstance() with Any type.


Paradox

Interestingly, when using cast(Any, CassandraConnection), Mypy accepts the typing without issues. In other words, when i cast Any to CassandraConnection, Mypy does not raise any errors, even though the underlying type is still Any. Here's the example:

TransactionalConnection: TypeAlias = cast(Any, CassandraConnection) -> This works with no MyPy errors.

This behavior is paradoxical because, in both cases: (isinstance and cast), the underlying type is Any, but Mypy handles them differently.


Full Scenario Example

# Core
import json
import os
from typing import TypedDict, TypeAlias, cast, Any

# Libraries
from psycopg2.extensions import connection as PostgreSQLConnection
import psycopg2
from psycopg2 import sql as psycopg2_sql
from cassandra.cluster import Session as CassandraConnection    # type: ignore
from cassandra.auth import PlainTextAuthProvider    # type: ignore
from cassandra.cluster import Cluster

# Core functionality
sql = psycopg2_sql
SqlCursor = psycopg2.extensions.cursor

# Defining type aliases
RelationalConnection: TypeAlias = PostgreSQLConnection
TransactionalConnection: TypeAlias = cast(Any, CassandraConnection)

class DbConnections(TypedDict):
    transactional: TransactionalConnection
    relational: RelationalConnection

Here’s the part where the isinstance check causes the error:

if isinstance(db_client, TransactionalConnection):  
    pass

error: Cannot use isinstance() with Any type

But when using cast, MyPy doesn't raise any errors:
TransactionalConnection: TypeAlias = cast(Any, CassandraConnection)


Conclusion

The inconsistent behavior between using isinstance() and cast when dealing with the Any type seems to be a bug or, at the very least, an inconsistency in Mypy. If cast() accepts Any without issue, isinstance() should behave similarly, as both deal with the Any type. However, Mypy rejects isinstance, but accepts cast.

This inconsistent behavior can confuse developers working with modules that lack proper typing, requiring the use of # type: ignore. I hope this issue can be reviewed, and Mypy can offer consistent behavior between isinstance and cast.


Environment

  • Python version 3.12.3
  • Flags: --strict
  • mypy version: 1.11.0
  • mypy-extensions version: 1.0.0

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、mypy 1.11.0 と --strict を使って最小限の Python 3.12 の例を再現し、次に isinstance() と cast() が無視された import 由来の Any 型をどのように扱うかを追跡します。意図された一貫性を確認し、報告された動作を対象とするリグレッションテストを追加します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。