简体   繁体   English

如何在python中键入提示nametuple?

[英]How to type hint nametuple in python?

Type hint can define the return type in python, so when a function return namedtuple type, then how to define it 类型提示可以在python中定义返回类型,因此当函数返回namedtuple类型时,该如何定义它

def bar(func):
    def decorator(*args, **kwargs):
        return namedtuple('data', 'name user')(**func(*args, **kwargs))

    return update_wrapper(decorator, func)


@bar
def info() -> NamedTuple:
    return {'name': 'a1', 'user': 'b1'}

Expect type 'NamedTuple',got Dict[str,str] instead 期望类型为“ NamedTuple”,而不是Dict [str,str]

As you know, the function info() return Dict[str, str] , but the decorator @bar change it. 如您所知,函数info()返回Dict[str, str] ,但装饰器@bar更改。 Now the function info() return a namedtuple object,so is there a way to indicate that the function info() return namedtupe object by type hint in python? 现在,函数info()返回namedtuple对象,那么有没有办法通过python中的hint来指示函数info()返回namedtupe对象?

NamedTuple instances are created via collections.namedtuple() function. NamedTuple实例是通过collections.namedtuple()函数创建的。

Since you are interested in typing elements of namedtuple, you could create a custom type that inherits the typed version of NamedType (as mentioned by @jab) and use it in type hints as shown below. 由于您对键入namedtuple的元素感兴趣,因此可以创建一个自定义类型,该类型继承NamedType的类型化版本(如@jab所述),并在类型提示中使用它,如下所示。

from typing import NamedTuple

class CustomType(NamedTuple):
    name: str
    user: str

def info() -> CustomType:
    return CustomType('a1', 'b1')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM