gpt4 book ai didi

python - 使用函数的返回类型指定类型提示

转载 作者:行者123 更新时间:2023-12-05 03:58:29 24 4
gpt4 key购买 nike

我想提示变量的类型作为特定函数的返回类型,(无需手动指定函数的返回类型是什么)。

我无法以可用作另一个变量提示的方式从函数中提取返回值类型。

def dostuff() -> T:
StuffContainer = namedtuple("StuffContainer", ["x", "y"])
return StuffContainer(1, 2)

def getX(a : T):
return a.x

我想要完成的 C++ 等价物:

auto dostuff() {
struct data {
int x;
int y;
};
return data {1, 2};
}

int getX(decltype(dostuff()) a) {
return a.x;
}

最佳答案

在 PEP 484 打字生态系统中没有等同于 decltype 的东西。更广泛地说,实际上并没有一种很好的方式来表达“匿名”类型。

因此,您输入代码的规范方式是执行更像这样的操作:

StuffContainer = namedtuple("StuffContainer", ["x", "y"])

def dostuff() -> StuffContainer:
return StuffContainer(1, 2)

def getX(a: StuffContainer):
return a.x

如果担心您返回的类型太长且不方便写出,您可以使用 type aliases 将其缩短一点:

StuffContainer = namedtuple("StuffContainer", ["x", "y"])

# S is now an alias of StuffContainer. The two types can be
# used interchangeably.
S = StuffContainer

def dostuff() -> S:
return StuffContainer(1, 2)

def getX(a: S):
return a.x

如果您担心的是您不想对 dostuff 返回 特别是 namedtuple 进行编码,并且您只想 promise 返回一些带有 'x 的对象' 和 'y' 属性,您或许可以使用协议(protocol)——您可以找到有关它们的更多信息 in the PEPmypy docs . (不幸的是,官方 Python 键入模块文档中还没有关于它们的任何信息。)

例如:

from typing import NamedTuple

# If you're using Python 3.8+, you can do:
from typing import Protocol

# If you want to support older versions of Python,
# run 'pip install typing_extensions' and do the below instead
from typing_extensions import Protocol

# Any type that has 'x' and 'y' attributes is compatible with this.
class HasXAndY(Protocol):
# Making these properties to declare that they're read-only,
# for maximum flexibility.
@property
def x(self) -> int: ...
@property
def y(self) -> int: ...


def dostuff() -> HasXAndY:
# Note: I'm switching to a version of namedtuple that lets me associate
# types with each field, mostly just for demonstration purposes. At runtime,
# it behaves identically to collections.namedtuple.
StuffContainer = NamedTuple("StuffContainer", [("x", int), ("y", int)])
return StuffContainer(1, 2)

def get_x(obj: HasXAndY) -> int:
return obj.x

# Type-checks
get_x(dostuff())


class Unrelated:
def __init__(self, x: int, y: int, z: int) -> None:
self.x = x
self.y = y
self.z = z

# Also type-checks
get_x(Unrelated(1, 2, 3))

关于python - 使用函数的返回类型指定类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57904492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com