Initial custom attributes work #1144
Draft
+141
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR enables other libraries to define their own Attribute classes (replacing attrs.Attribute), and hence to define their own
fields()
function.Why does this need to be in attrs?
Because the next step will be to add support for this to the attrs Mypy plugin, and we need to design this feature with that in mind.
Having Mypy support for this will actually enable statically checking things that were previously impossible in Python, so if we do it right, it might be a big deal.
For example, as far as I know no ORM in Python today can statically check queries. We may change this.
Since this is a feature for library authors (not end users directly), we may consider designing it so it is easily supportable in Mypy rather than easy to use (as funny as that sounds).
My personal motivation is that my codebases are pretty heavily typed, but I keep running into untypeable things to do with databases. I would love to plug the hole, even partially.
This is a continuation of #934.
Use cases
cattrs customization
Right now, here's how a cattrs structuring function can be customized:
Here's how it could be:
Why is it better?
A more fluent API, better errors, statically checked.
cattrs validation
cattrs has no validation right now, here's how it could work.
PocketMongo query builder
The current approach to creating a Mongo query condition:
How it could be:
Why is it better:
A more fluent API. Statically checked.
This might end up being a model for attrs-based ORMs going forward.
Problems
Pyright probably won't support this, but that's just something we have to live with. Mypy supporting it will add plenty of value.
I'm not sure about handling nested attributes yet. If class A has an attribute
b
, typed as classB
, and classB
has a field calledc
.f(A).b.c
should probably work, but it maybe requires special casing? That's TBD, but sounds like mostly a Mypy issue.