与 Mypy 兼容的类装饰器 [英] Class Decorator Compatible for Mypy

查看:27
本文介绍了与 Mypy 兼容的类装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下没有任何类型提示的简单示例:

Say I have the following simple example without any typehints:

def wrapper(cls):
    class Subclass(cls):
        def subclass_method(self):
            pass
    return Subclass


@wrapper
class Parent:
    def parent_method(self):
        pass


p = Parent()
p.parent_method()
p.subclass_method()

如何使用类型提示重构此代码,以便当我针对 Parent 的实例运行 mypy 时,它会同时识别 subclass_methodparent_method?

How can I restructure this code using typehints, such that when I run mypy against an instance of Parent, it will recognize both subclass_method and parent_method?

可能的解决方案:

  • 使用 mixin Parent(Mixin):有效,但避免使用装饰器.没有可能实现吗?
  • 将方法修补到现有类上:在 mypy 中解决 subclass_method 仍然存在相同的问题
  • 自定义 Mypy 插件:不确定从哪里开始使用这个插件,或者如果没有它是否可行.
  • Using a mixin Parent(Mixin): Works, but avoids the decorator. Is it possible to achieve without?
  • Patching the method onto the existing class: Still has the same issue of resolving subclass_method in mypy
  • Custom Mypy plugin: Wouldn't be sure where to start with this one, or if it would be possible without one.

推荐答案

如果没有包装器,这会简单得多.

This would be much simpler without the wrapper at all.

class SomeMixin:
    def subclass_method(self):
        pass


class Parent(SomeMixin):
    def parent_method(self):
        pass


p = Parent()
p.parent_method()
p.subclass_method()

在这里,您定义 SomeMixin 一次,而不是每次调用包装器一次,并且类 SomeMixin 是静态已知的.所有名称为Subclass 的各种类都是动态创建的,mypy 无法静态知道哪个类是name Parent 实际上绑定到.

Here, you define SomeMixin once, not once per call to a wrapper, and the class SomeMixin is known statically. All the various classes with the name Subclass are created dynamically, and mypy can't know statically which class the name Parent is actually bound to.

这篇关于与 Mypy 兼容的类装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆