267 points · by ekiauhce · 3y ago · 149 comments
If your function just wraps another you can use the same type hints as the other function with functools.wraps https://docs.python.org/3/library/functools.html#functools.w...
Underneath, this is because many (most?) type checkers for Python aren't actually running the code in order to access annotation information, and are instead parsing it "from the outside" using complex and fallible techniques of variable reliability. That said, it's a testament to JetBrains' excellent work that PyCharm's checker works as well as it does, given how crazily metaprogrammed even simple Python often turns out to be.
I recently switched from Pycharm to vscode which uses pyright and it's night and day on the amount of type errors it catches, it considerably improved the quality of my code and confidence during refactoring.
And to add insult to injury Pycharm doesn't even have a pyright plugin and the mypy plugin is extremely slow and buggy.
Their Python support has t kept up with other tools as noted. I’ve see a similar decline in the ability for for them to keep up to date with things like Svelte, Vue, Astro etc too.
They need to embrace the LSP
https://docs.python.org/3/library/typing.html#typing.ParamSp...
Not ideal but not too bad either.
Forge: forge (python signatures) for fun and profit
Moving to static Python in most places has dramatically improved the code and language.
Kwargs everywhere, often only defined for a type at runtime by spooky voodoo action at a distance metaclass shenanigans...
Essentially super().__init__() will resolve to a statically unknowable class at run-time because super() refers to the next class in the MRO. Knowing what class you will call is essentially unknowable as soon as you accept that either your provider class hierarchy may change or you have consumers you do not control. And probably even worse, you aren't even guaranteed that the class calling your constructor will be one of your subclasses.
Which is why for example super().__init__() is pretty much mandatory to have as soon as you expect that your class will be inherited from. That applies even if your class inherits only from object, which has an __init__() that is guaranteed to be a nop. Because you may not even be calling object.__init__() but rather some sibling.
So the easiest way to solve this is: Declare everything you need as keyword argument, but then only give **kwargs in your function signature to allow your __init__() to handle any set of arguments your children or siblings may throw at you. Then remove all of "your" arguments via kwargs.pop('argname') before calling super().__init__() in case your parent or uncle does not use this kwargs trick and would complain about unknown arguments. Only then pass on the cleaned kwargs to your MRO foster parent.
So while using **kwargs seems kind of lazy, there is good arguments, why you cannot completely avoid it in all codebases without major rework to pre-existing class hierarchies.
For the obvious question "Why on earth?" These semantics allow us to resolve diamond dependencies without forcing the user to use interfaces or traits or throwing runtime errors as soon as something does not resolve cleanly (which would all not fit well into the Python typing philosophy.)
Instead, I've come to prefer a style I took from Julia: every class is either (a) abstract, or (b) concrete and final.
Abstract classes exist to declare interfaces.
__init__ methods only exist on concrete classes. After that it should be thought of as unsubclassable, and concerns about inheritance and diamond dependencies etc just don't exist.
(If you do need to extend some functionality: prefer composition over inheritance.)
The easiest way is to not put your arguments into kwargs in the first place. If you put them as regular function arguments (probably give them a default value so they look like they're related to kwargs), then the python runtime separates them from the rest when it generates kwargs and you don't have to do the ".pop()" part at all.
To do otherwise would require some form of vararg generics which is uncommon.
def variable(n:str, nn:str, nnn:str, *, a:int, b:int, c:int)
Anything after,*, is a kwarg.
def sum(*args: int) -> int:
if len(args) == 0:
return 0
return args[0] + sum(*args[1:])GP is suggesting that one should only ever use explicit keyword-only args (anything listed after `*,` in the signature) versus arbitrary keyword args implicit via `**kwargs`.
e.g. (omitting type hints for clarity):
def sum(*args, **arbitrary_kwargs):
...
vs def sum(*args, some_keyword_only_arg):
...
In my opinion if one finds themselves writing code that uses arbitrary kwargs, they've got a design problem.**`a[1:]` returns the sequence of elements that start at index 1. If there is no such element, the list is empty. I don’t see any good reason why this should throw an error.
When using slice notation, the return value is a sequence, so returning a zero-length sequence is sufficient to communicate you asked for more items than exist.
It may be surprising, but it almost always leads to more ergonomic code.
print(firstname, lastname)
for example is more readable than print((firstname, lastname))
especially since I would then have to write print((surname,))
to just print a single string.Variadic functions are rather classic, I think Go, Rust, C and JavaScript also have them.
The wrapper is usually some shorthand for building a handful of those args or adding some side-effect, while still allowing the caller access to the remaining config options via kwargs.
Here's one example of that in the wild https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot....
[0] actually 3 positional-or-keyword which is even more widely divergent
It's certainly debatable whether doing that is better than passing a single argument whose value is a dict with that same type, but many people do prefer the variadic args/kwargs style.
I would rather:
@dataclass(frozen=True, slots=True)
class VarThings:
n: int
...
def variable(a: VarThings):
...
Than a million argsA required positional OR kwarg as you’ve done it. Its closer to an optional kwarg if you expand the type declaration to also allow None and set a None default.
But there are times when you want to leave the number and names of kwargs open (one example is for a dynamic wrapper—a function that wraps another function that can be different across invocations.)
subprocess.run() is an example of that. Also check out the functions in manim.
The inability to properly static type kwargs using TypedDict is probably the biggest flaw in Python's type hint system (after the fact that hardly anyone uses it of course).
https://stackoverflow.com/questions/47060133/python-3-type-h...
what a disaster
This always bugs me: why is `args` immutable (tuple) but `kwargs` mutable (dict)? In my experience it’s much more common to have to extend or modify `kwargs` rather than `args`, but I would find more natural having an immutable dict for `kwargs`.
Because python didn’t (still doesn’t, but at this point even if it did backward compatibility would mean it wouldn’t be used for this purpose) have a basic immutable mapping type to use.
(Note, yes, MappingProxyType exists, but that’s a proxy without mutation operations, not a basic type, so it costs a level of indirection.)
In my experience, people who don’t care about tuples are people who don’t understand them. It’s not much about being Pythonic or not (they exists in other languages) but rather about choosing the right data structure for solving your problem. Tuples are much more than a way of making immutable lists, they offer a type-safe and serializable representation of pairs and triplets; something you can’t have with a list. If you don’t use them yet, I really encourage you to document yourself (and again-- in general, not just in Python) because you’re missing something.
A language being statically typed or dynamically typed is a design decision with implications for what the language can do. There are benefits to each method of programming.
Trying to strap type checking on to Python is born out of some misplaced belief that static type is just better. Using Python as a dynamically typed language allows you for certain programming patterns that cannot be done in a statically typed language. There are some great examples in SICP of Scheme programs that could not exist (at least with as much elegance) in a typed language. Dynamic typing allows a language to do things that you can't do (as easily/elegantly) in a statically typed language.
Some may argue that these type of programming patterns are bad for production systems. For most of these arguments I strongly agree. But that means for those systems Python is probably a poor choice. I also think metaprogramming is very powerful, but also a real potential footgun. It would be ridiculous to attempt to strip metaprogramming from Ruby to make it "better", just use a language that depends less on metaprogramming if you don't like it.
This is extra frustrating because in the last decade we've seen the options for well designed, statically typed languages explode. It's no longer Python vs Java/C++. TypeScript and Go exist, have great support and are well suited for most of the domains that Python is. Want types? Use those languages.
Most of my work is in machine learning/numeric computing, so I'm very familiar with the benefits of Python's ecosystem. Basically all of AI/ML work is about prototyping ideas rapidly, where access to libraries and iterating fast greatly trumps the need for type safety.
At nearly every place I've worked, Python is the tool for building models quickly but shipping them to production and integrating them with the core product almost always involves another language, typically with types, better suited for large engineering teams working on a large code base where you really want some sort of type checking in place. Most of the companies I know that do serious ML in production typically take models from python and then implement them in either C++ or Scala for the actual production serving.
It's worth pointing out that the vast majority of those libraries you use were initially developed without any consideration, or need, for types. Great, reliable, software can be written without types. Dynamic typing is a great language choice, and there's no need to fight the language itself by trying to bolt types on.
Where types are important is where you have a complex, rapidly changing code base with a large number of developers of differing skill levels releasing frequently. If that's the environment you're in, I would strongly recommend against using Python in prod, even if it means you have to implement the features of some libraries internally.
Funnily enough, Python has Go-esque types also, Protocols, and they have the exact same issue. I only use them when I really really need structural typing to reuse code in a typesafe way.
Autocomplete and type-checking are massive boons to writing "type-correct" code, fast. It doesn't guarantee that your code won't explode at runtime or is logically correct (that's what tests are for), but it does help eliminate an entire class of bugs, and, again, speeds up development a massive amount when dealing with very large codebases.
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,...))`.
Given:
def foo(*args):
print(args)
return
class Thing(object):
def __init__(self,a,b):
self.a = a
self.b = b
return
def foo_style(self):
return (self.a, self.b)
args is not required to refer to a tuple: >>> foo(*[31,42])
(31, 42)
I can have objects construct parameters conforming to the specifications for a signature: >>> foo(*Thing(3,91).foo_style())
(3, 91)
Consider that a counterexample.https://qiskit.org/ecosystem/aer/stubs/qiskit_aer.primitives...
I work in a large python codebase, we have almost no usage of `*kwargs` beyond proxy methods because of the nature of how they obfuscate the real interface for other developers.
Maybe in some use case people need to merge 2 functions into 1, I don't know if it can handle this situation.
If you are referring to a type signature for a function that passes through it's arguments to one of two inner functions, each of which has different signatures, such that the outer signature accepts the union of the two inner signatures, well ... you could achieve that with ParamSpecs or similar, but it would be pretty hard to read and indirected. Better, I'd say, to manually express appropriate typing.Union (|) annotations on the outer function, even if that is a little less DRY.
If you're not going to document something (which I totally respect), at least don't make the code worse while doing it.