Live data from Hacker News

Python Type Hints – *args and **kwargs (2021)

adamj.eu

1–10 of 158 posts

Re: Python Type Hints – *args and **kwargs (2021)

#3
Alternatively, use an `@overload` in a `.pyi` file and specify your types there.

This means that you will have 2^N combinations and doubling every time you accept a new argument.

If that is not good enough, then simply use a `TypedDict` with everything optional instead of `**kwargs`. Your call will then become `foo(SomeTypedDict(p1=p2,...))`.

Re: Python Type Hints – *args and **kwargs (2021)

#5

This does restrict all of your keyword arguments to the same type. If you have keyword arguments of different types, you're right back to no type safety.

That seems obvious? If you want a variable number of arguments of arbitrary type you have to specify the common supertype, commonly top itself.

To do otherwise would require some form of vararg generics which is uncommon.

Re: Python Type Hints – *args and **kwargs (2021)

#6

Why do people not just type everything they want passed? def variable(n:str, nn:str, nnn:str, *, a:int, b:int, c:int) Anything after,*, is a kwarg.

Your signature requires exactly 3 positional[0] and 3 keyword arguments. The OP allows any number of either.

[0] actually 3 positional-or-keyword which is even more widely divergent

Re: Python Type Hints – *args and **kwargs (2021)

#7

Why do people not just type everything they want passed? def variable(n:str, nn:str, nnn:str, *, a:int, b:int, c:int) Anything after,*, is a kwarg.

It is used when the number of argument can vary, like:

    def sum(*args: int) -> int:
        if len(args) == 0:
            return 0
        return args[0] + sum(*args[1:])

Re: Python Type Hints – *args and **kwargs (2021)

#8
Although these two comes in handly, people have been using them wrong. Often in scientific open source package, they slap *kwargs in function definition without documentation. How am I suppose to know what to pass in?

https://qiskit.org/ecosystem/aer/stubs/qiskit_aer.primitives...

Post reply on HN