TypeVar
和NewType
似乎相关,但是我不确定何时应该使用它们,或者在运行时和静态地使用什么区别。
参考方案
这两个概念与其他任何与类型相关的概念都没有更多的关联。
简而言之,TypeVar
是一个可以在类型签名中使用的变量,因此您可以多次引用同一未指定的类型,而NewType
则用于告诉类型检查器某些值应视为自己的值类型。
Type Variables
为简化起见,类型变量使您可以多次引用同一类型,而不必确切指定其类型。
在定义中,单个类型变量始终采用相同的值。
# (This code will type check, but it won't run.)
from typing import TypeVar, Generic, List, Tuple
# Two type variables, named T and R
T = TypeVar('T')
R = TypeVar('R')
# Put in a list of Ts and get out one T
def get_one(x: List[T]) -> T: ...
# Put in a T and an R, get back an R and a T
def swap(x: T, y: R) -> Tuple[R, T]:
return y, x
# A simple generic class that holds a value of type T
class ValueHolder(Generic[T]):
def __init__(self, value: T):
self.value = value
def get(self) -> T:
return self.value
x: ValueHolder[int] = ValueHolder(123)
y: ValueHolder[str] = ValueHolder('abc')
没有类型变量,就没有办法声明get_one
或ValueHolder.get
的类型。
TypeVar
上还有其他一些选项。您可以通过传入更多类型来限制可能的值(例如TypeVar(name, int, str)
),或者可以给出上限,以便类型变量的每个must值都必须是该类型的子类型(例如TypeVar(name, bound=int)
)。
此外,您可以在声明类型变量时决定其类型是协变,逆变还是两者都不是。这从本质上决定了何时可以使用子类或超类代替泛型类型。 PEP 484 describes these concepts更为详细,并涉及其他资源。
NewType
NewType
用于当您想要声明一个不同的类型而又不实际执行创建新类型的工作或担心创建新类实例的开销时。
在类型检查器中,NewType('Name', int)
创建名为的int
子类。
在运行时,NewType('Name', int)
根本不是一个类。它实际上是标识函数,因此x is NewType('Name', int)(x)
始终为true。
from typing import NewType
UserId = NewType('UserId', int)
def get_user(x: UserId): ...
get_user(UserId(123456)) # this is fine
get_user(123456) # that's an int, not a UserId
UserId(123456) + 123456 # fine, because UserId is a subclass of int
对于类型检查器,UserId
看起来像这样:
class UserId(int): pass
但是在运行时,UserId
基本上就是这样:
def UserId(x): return x
在运行时,NewType
几乎没有什么比这更重要的了。从Python 3.8开始,其implementation几乎完全如下:
def NewType(name, type_):
def identity(x):
return x
identity.__name__ = name
return identity
在返回'Response'(Python)中传递多个参数 - python我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
Python exchangelib在子文件夹中读取邮件 - python我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
Python ThreadPoolExecutor抑制异常 - pythonfrom concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…
Python GPU资源利用 - python我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…