python / python/mypy

Is it possible to define a subscriptable class which can take type arguments and ellipses?

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

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

feature question topic-metaclasses
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

  • Are you reporting a bug, or opening a feature request?

More of a feature request/question.

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.

The following is a mock up and not fully implemented. I would like to define a class for which the defined functions and the statements written in main() will not raise mypy errors with the config file I've given below. Or at least I would like to know if this is possible or not.

from typing import Any, TypeVar
from functools import lru_cache

T = TypeVar("T")


class SubscriptableType(type):
    """ Generic metaclass for subscriptable type. """

    def __init_subclass__(cls) -> None:
        cls._hash = 0

    @lru_cache()
    def __getitem__(cls, item: Any) -> type:
        body = {
            **cls.__dict__,
            "__args__": item,
            "__origin__": cls,
        }
        bases = cls, *cls.__bases__
        result = type(cls.__name__, bases, body)
        return result

    def __eq__(cls, other: Any) -> bool:
        cls_args = getattr(cls, "__args__", None)
        cls_origin = getattr(cls, "__origin__", None)
        other_args = getattr(other, "__args__", None)
        other_origin = getattr(other, "__origin__", None)
        args_eq: bool = cls_args == other_args
        origins_eq: bool = cls_origin == other_origin
        is_eq: bool = args_eq and origins_eq
        return is_eq

    def __hash__(cls) -> int:
        """ TODO: implement. """
        if not getattr(cls, "_hash", None):
            cls._hash = 0
        return cls._hash


class AMeta(SubscriptableType):
    pass


class AType(metaclass=AMeta):
    pass


def function_1(x: AType[int]) -> AType[int]:
    return x


def function_2(x: AType[...]) -> AType[...]:
    return x


def function_3(x: AType[None]) -> AType[None]:
    return x


def main() -> None:
    x = 0
    isinstance(x, AType[int])
    isinstance(x, AType[...])

  • What is the actual behavior/output?

Given the following mypy config:

[mypy]
check_untyped_defs = true
disallow_untyped_defs = true
ignore_missing_imports = true
no_implicit_optional = true
warn_redundant_casts = true
warn_return_any = true
warn_unused_ignores = true
show_error_codes = true

# Ignore all torch type errors.
[mypy-torch.*]
follow_imports = skip
follow_imports_for_stubs = True

Mypy output:

asta/demo.py:49: error: "AType" expects no type arguments, but 1 given  [type-arg]
asta/demo.py:53: error: Unexpected '...'  [misc]
asta/demo.py:53: error: "AType" expects no type arguments, but 1 given  [type-arg]
asta/demo.py:57: error: "AType" expects no type arguments, but 1 given  [type-arg]
  • What is the behavior/output you expect?
    I would like the above to raise no mypy errors for someone using the class AType in their own projects. I'm fine with disabling errors in the source code of the class/metaclass definitions, but I would like to be able to use AType in place of a subscriptable generic type in type hints, and raise no errors if passed None, ..., '(int, int), or intfor example. Inheriting fromGeneric[T]is out of the question because it will make mypy complain aboutisinstance()` checks.

  • What are the versions of mypy and Python you are using?

Python 3.7.6
Mypy 0.761

Do you see the same issue after installing mypy from Git master?
I trying to determine if this is possible for the latest version available from pip.

  • What are the mypy flags you are using? (For example --strict-optional)
    See above. Ran with mypy <directory>.

  • If mypy crashed with a traceback, please paste
    the full traceback below.
    Did not crash.

(You can freely edit this text, please remove all the lines
you believe are unnecessary.)

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

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

はじめの一歩

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

調査の方向性

issue にある最小限の AType/AMeta repro から始め、示されている mypy の設定とバージョン情報で実行します。この subscriptable class について、アノテーションや isinstance() チェックでエラーを発生させずに任意の型引数と省略記号を mypy がサポートできるかを確認します。要求された用法が正常に type-check されるか、制限事項が文書化されていれば完了です。

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

評価

技術スタック
python
領域
devtools
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

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

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