在Python中的 TypeScript Parameters 辅助函数的等效物。

huangapple go评论79阅读模式
英文:

Equivalent of Parameters helper from typescript in python

问题

在TypeScript中,有一个Parameters辅助工具,用于获取函数参数中的所有类型:

function sum(a: number, b: number) {
  return a + b
}
type SumParameters = Parameters<typeof sum>;
function subtract(...params: SumParameters) {
  return a - b
}

在Python中,要实现类似的功能,你可以使用函数注解和类型提示。以下是Python的示例代码:

from typing import Tuple

def sum(a: int, b: int) -> int:
    return a + b

def subtract(*params: Tuple[int, int]) -> int:
    a, b = params
    return a - b

这里我们使用了Tuple[int, int]来指定参数的类型,并在函数上使用了类型提示来指定返回类型。这样,你不需要重新声明所有类型,Python会自动根据注解推断类型。

英文:

In typescript it has a Parameters helper that get all types from function arguments:

function sum(a: number, b: number) {
  return a + b
}
type SumParameters = Parameters&lt;typeof sum&gt;;
function subtract(...params: SumParameters) {
  return a - b
}

How can I do the same in python so I don't need to redeclare all types again?

This question is different from https://stackoverflow.com/questions/74275831/pythons-equivalent-of-typescripts-parameters-utility-type once it's asking for ConstructorParameters

答案1

得分: 2

TypeScript 可以轻松做到这一点,因为构建步骤涉及在传递之后重写源代码,所以 "魔法命名参数" 可以在函数签名中突然出现,实际生成的 JavaScript 文件将明确包含它们。

Python 可以在运行时做很多事情,但如果您想要一个函数能够具有 "任意" 签名,它必须接受一个序列和一个参数映射,形式如 def myfunc(*args, **kwargs): ,并且可以编写一个装饰器,该装饰器将在运行时显示从另一个函数克隆的签名。

然而,运行时不是静态类型解析时间,我认为当前的工具对于这方面没有等效的工具,但可以读取源代码 (.py) 文件,并生成带有注释的存根文件 (.pyi),其中包含显式参数。

但是,如果有人想要这样做,只需简单地复制参数声明和它们的注释到要与其他函数相等的函数中,这将更加简单和可读,只需复制参数声明和它们的注释到要与其他函数相等的函数中。

换句话说,可以编写如下内容:

def sum(a: int, b: int):
    return a + b

@parameters(sum)
def sub(**kwargs):
   return kwargs["a"] - kwargs["b"]

然后需要一个在静态类型检查器之前运行的工具,它将导入该代码并生成一个带有签名 "sub (a: int, b: int): ..." 的存根 ".pyi" 文件,但您将无法直接在 sub 的主体中使用 "a" 和 "b",这将非常繁琐。

至于参数本身:它们在函数调用中是硬编码的。

Python 在 __annotations__ 属性中记录类型信息 - 该属性是可写的。

再次强调,虽然语言可以在运行时简单地从一个函数复制 __annotations__ 到另一个函数,但静态类型检查器不会知道它。

英文:

TypeScript can do that easily because the build steps involve rewriting the source code after a pass - so "magic named parameters" can appear from nowhere in function signatures, and the actual generated JavaScript file will feature them explicitly.

Python can do a lot of that at runtime - but if you want a function that can have "any" signature, it has to take in a sequence and a mapping of parameters in the form def myfunc(*args, **kwargs): - and it is possible to write a decorator that would show, at runtime, the signature as cloned from another function.

However, runtime is not static-type-parsing time, and I think the current tools have no equivalent for that, but for something that would
read the source code (.py) file, and generate a stub file with the annotations (.pyi), with the explicit parameters.

But, if one gets to this, it is straightforward and an order of magnitude easier and more readable, just copy around the parameter declaration and their annotations to functions meant to be equal others.

In other words, it would be possible to write something along:

def sum(a: int, b: int):
    return a + b

@parameters(sum)
def sub(**kwargs):
   return kwargs[&quot;a&quot;] - kwargs[&quot;b&quot;]

And you'd need a tool to run before the static type checker that would import that and generate a stub ".pyi" file with the signature "sub (a: int, b: int): ..." - but you would not be able to make use of "a" and "b" in the body of sub directly - which would be very cumbersome.

As for the parameters themselves: they are hardcoded in the function call.

Python records typing information in an __annotations__ attribute - that attribute is writeable.

Again, while the language can simply copy __annotations__ from one function to the other at runtime, the static type checkers won't know about it.

答案2

得分: 1

在Python中没有等价的。您需要明确定义参数(不仅是它们的类型)。

def sum(a: int, b: int):
    return a + b

def subtract(a: int, b: int):
    return a - b
英文:

There is no equivalent in Python. You need to define the parameters (not just their types) explicitly.

def sum(a: int, b: int):
    return a + b


def subtract(a: int, b: int):
    return a - b

huangapple
  • 本文由 发表于 2023年2月23日 22:01:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定