by dcreager · 12h ago · 0 comments
But (1) django is older than Python's type system, so it uses some very dynamic patterns that are hard to express using Python types. And (2) it's very popular, which means both that lots of people want their type checker to do Something Useful™ with django code, and that it would be very difficult to retrofit django to use dynamic patterns that _are_ more compatible with the type system. That combination makes it worth our time to add specific custom support for it.
For your own future library, the hope is that the type system has become capable enough that you wouldn't _need_ custom type checker support. Things like `dataclass_transform` [1] were added specifically so that _all_ libraries could express these kinds of things in ways that are visible to the type checkers without custom support.
If you're doing something that still doesn't fit into what the typing system provides, then the Python typing community wants to learn about your use case so that we can see if we can extend the typing system even further to support it.
[1] https://typing.python.org/en/latest/spec/dataclasses.html
- Adding field X also adds field x_pk
- Adding field X also changes the signature of function Y to accept parameter x, x__lt, x__gt, etc.
- Adding field X lets you do a.x = 5, even though X is not really an integer
As an aside, I have to give it to the Typescript team for taking Javascript which was fundamentally as metaprogramming happy as Python, and creating a type system that matched it. Having a goal that every popular pattern in Javascript should be type-checked was a great starting choice, because they couldn't simply copy some other languages' static typing methadology and had to work from teh ground up.
All of these are known deficiencies. Everyone who brings them up is told to pound sand, their use cases deemed illegitimate. Might as well be GNOME.
It's fundamentally unfair that Django gets to use aspects of the language other tools can't, and one hard coded dataclass-style transform is inadequate.
So help me God, if I ever do another large scale Python project, then if these issues aren't fixed in typing, I will vendor and modify a type checker in the project itself and teach it my project's patterns directly. I will not twist and distort my design vision so it rhymes with dataclass.
You can just ... not typecheck parts of your code. All of these tools are gradual, since Python's much too dynamic to encompass everything. Falling back to runtime "I know how this works" dynamism isn't a sin, it just requires a little care. Add restrictions (typed wrappers, verbosity/limitations a la dataclass_transform) at the boundaries where people make frequent mistakes, and move on with your life.