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<typeof sum>;
function subtract(...params: SumParameters) {
return params[0] - params[1]
}
How can I do the same in python so I don't need to redeclare all types again?
This question is different from Python's equivalent of Typescript's Parameters utility type? once it's asking for ConstructorParameters
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["a"] - kwargs["b"]
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.