Where DRY Applies
v5.chriskrycho.com
v5.chriskrycho.com
My new thing lately has been JSON schemas.
I use them to set defaults, to decide what properties to save and load, to eliminate unnecessary defaults when saving, to generate __slots__, and for verifying correctness at different steps in the program, like when accepting data from an API call.
I'm still using manual type annotations though, it doesn't seem like there are common tools for making a class from a schema in a way that MyPy understands.
They also serve as the source of truth documentation for the data. I'm not sure why I didn't start using them a long time ago!
I wonder what other similarly powerful DRY tools I'm not using but should be?
In the TypeScript world, there are a number of libraries that can handle creating types from deserialization logic: Zod [1], Superstruct [2], Typebox [3], etc. – and Typebox specifically does what you are looking to do with MyPy. I do not know the Python ecosystem at all anymore (it has been a decade!) but I would be surprised if nothing like that exists. If it does, there is a good chance it is associated with the functional programming enthusiast corner of the Python community, so you might look there!
[1]: https://github.com/colinhacks/zod
Python definitely does have tools like that, but many haven't been touched in a few years, and Python code sadly has a shelf life, although it seems to slowly be stabilizing.