小编Enr*_*aud的帖子

如何在 Python 元类中键入 __new__ 方法让 mypy 开心

我正在尝试__new__在 Python 的元类中键入该方法,以便它使 mypy 满意。代码将是这样的(取自pep-3115 - “Python 3000 中的元类”并精简了一点):

from __future__ import annotations

from typing import Type


# The metaclass
class MetaClass(type):

    # The metaclass invocation
    def __new__(cls: Type[type], name: str, bases: tuple, classdict: dict) -> type:
        result = type.__new__(cls, name, bases, classdict)
        print('in __new__')
        return result


class MyClass(metaclass=MetaClass):
    pass
Run Code Online (Sandbox Code Playgroud)

有了这个,mypy 抱怨说,Incompatible return type for "__new__" (returns "type", but must return a subtype of "MetaClass"),指着线def __new__

我也试过:

def __new__(cls: Type[MetaClass], name: str, bases: …
Run Code Online (Sandbox Code Playgroud)

python metaclass typing

6
推荐指数
1
解决办法
1175
查看次数

标签 统计

metaclass ×1

python ×1

typing ×1