python / python/mypy

Metaclass defined class attribute raise "name-defined" error when used as a type

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

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

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

説明

Using a Metaclass to define dynamic class (not instance) attributes raises name-defined error when trying to use an attribute as a type.

To Reproduce

Gist URL: https://gist.github.com/mypy-play/bb0277c6f339cbf374a1d2288cb7d5e6

Playground URL: https://mypy-play.net/?mypy=latest&python=3.12&gist=bb0277c6f339cbf374a1d2288cb7d5e6

from enum import Enum

class Message:
    class Direction(Enum):
        IN = "IN"
        OUT = "OUT"


class MetaProtoWrapper(type):
    def __getattribute__(cls, name: str):
        try:
            return super().__getattribute__(name)
        except AttributeError:
            return getattr(cls.Meta.protocol_buffer_type, name)


class ProtoWrapper(metaclass=MetaProtoWrapper):
    class Meta:
        protocol_buffer_type = Message


direction_in = ProtoWrapper.Direction.IN  # OK
direction_in: ProtoWrapper.Direction = ProtoWrapper.Direction.IN   # Name "ProtoWrapper.Direction" is not defined  [name-defined]

Expected Behavior

ProtoWrapper.Direction should be a valid type

Actual Behavior

ProtoWrapper.Direction raises name-defined error

Your Environment

  • Mypy version used: mypy 1.10.0 (compiled: yes)
  • Mypy command-line flags: NA
  • Mypy configuration options from mypy.ini (and other config files): NA
  • Python version used: 3.12

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

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

はじめの一歩

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

調査の方向性

リンクされた mypy-play の再現コードまたは issue のコードを実行して、型として使用されるメタクラス提供のクラス属性で name-defined エラーが発生することを確認してください。その再現コードから mypy の関連する動作を追跡し、その後、ProtoWrapper.Direction がエラーなしで型として受け入れられることを確認してください。

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

評価

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

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

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