gpt4 book ai didi

python - 如何注释 Python 函数以提示它采用与另一个函数相同的参数?

转载 作者:行者123 更新时间:2023-12-03 14:23:21 25 4
gpt4 key购买 nike

是否有任何 Python 类型提示语法来声明一个函数采用与另一个函数相同的参数(和参数类型)?特别是这对于包装很有用,例如,

async def do_stuff(
param1: str,
param2: int,
param3: int = 14,
):
...

def run_async_thing(*args, **kwargs): # <--- What can I put here to say 'takes args like `do_stuff`'?
return asyncio.get_event_loop().run_until_complete(do_stuff(*args, **kwargs))

在这种情况下,我想向 run_async_thing 添加类型提示。函数来识别它期望与 do_stuff 相同的参数类型功能。

这是可能的,如果是,如何?

想要这个的主要原因是我的工具(特别是 PyCharm/IntellliJ IDEA)可以找出哪些参数 run_async_thing应该期待/接受。如果它有助于文档,那是一个奖励,但这主要用于工具。

最佳答案

明确定义参数。您不必要地概括了 run_async_thing 的签名:

def run_async_thing(p1: str, p2: int, p3: int):
return asyncio.get_event_loop().run_until_complete(do_stuff(p1, p2, p3))

更一般地说,您可以拥有 run_async_thing将单个元组(或其他对象)作为参数。例如:
async def do_stuff(t: Tuple[str, int, int]):
...

def run_async_thing(args: Tuple[str, int, int]):
return asyncio.get_event_loop().run_until_complete(do_stuff(args))

元组类型可以被分解:
StuffDoerArgs = Tuple[str, int, int]

async def do_stuff(t: StuffDoerArgs):
...

def run_async_thing(args: StuffDoerArgs):
...

关于python - 如何注释 Python 函数以提示它采用与另一个函数相同的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60387444/

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