Python类型提示:如何分辨X是Foo的子类? [英] Python type hinting: how to tell X is a subclass for Foo?

查看:73
本文介绍了Python类型提示:如何分辨X是Foo的子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何为Python中的类类型编写类型提示?
考虑以下代码:

How should I write a type hint for class types in Python? Consider this code:

class A(object):
    pass

class B(A):
    pass

def register(cls: type[A]):
    assert issubclass(cls, A)

 register(A)
 register(B)

类型[ A] 写这个的正确方法吗?
如果我只使用 cls:A ,则表示 cls 是<$ c的实例$ c> A ,但我想说的是 cls 是一个类/类型,其中至少子类 A

Is type[A] the correct way to write this? If I'd just use cls: A it would mean cls is an instance of A, but I want to to say cls is a class/type, which at least subclasses A.

具体来说,我想指出的是该参数应为
a Django模型类型。

Specifically, what I want to indicate is that the parameter should be a Django model type.

推荐答案

似乎其他当前答案(2016年9月22日)都不正确。根据PEP 484(关于类型提示),存在有关类对象类型的提示,称为类型[C] 。根据 typing 模块的文档,您可以使用 typing.Type [C] 即可实现所需的功能。我正在使用自己的Python 3.5.2。

It seems like other current (22 Sep 2016) answers here are incorrect. According to PEP 484 (about Type Hints), there exists a hint for type of class objects, called Type[C]. And according to typing module's documentation, you can use typing.Type[C] to achieve exactly what you want. I'm using those myself with Python 3.5.2.

引用 PEP


有时讨论类对象,特别是从给定类继承的类对象。可以将其拼写为Type [C],其中C是一个类。需要说明的是:C(用作注释时)是指类C的实例,而Type [C]是指C的子类。

Sometimes you want to talk about class objects, in particular class objects that inherit from a given class. This can be spelled as Type[C] where C is a class. To clarify: while C (when used as an annotation) refers to instances of class C , Type[C] refers to subclasses of C .

并引用文档


用C注释的变量可以接受类型C的值。相反,用Type [C]注释的变量可以接受类本身的值–特别是,

A variable annotated with C may accept a value of type C. In contrast, a variable annotated with Type[C] may accept values that are classes themselves – specifically, it will accept the class object of C.

并参考您的特定示例:

import typing

class A(object):
    pass

class B(A):
    pass

def register(cls: typing.Type[A]):
    assert issubclass(cls, A)

register(A)
register(B)

您可以使用 mypy ,它应该可以简单地工作案例-但是请注意mypy尚在开发中,截至目前,关于Type [C]提示存在一些问题。

You can check such code statically using mypy, and it should work in simple cases -- beware however that mypy is a work in progress, as of now there are several issues open about Type[C] hinting.

这篇关于Python类型提示:如何分辨X是Foo的子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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