Skip to content

Recognize many=True serializer constructors as ListSerializer - #968

Open
federicobond wants to merge 3 commits into
typeddjango:masterfrom
federicobond:serializer-many-list-kwargs
Open

Recognize many=True serializer constructors as ListSerializer#968
federicobond wants to merge 3 commits into
typeddjango:masterfrom
federicobond:serializer-many-list-kwargs

Conversation

@federicobond

Copy link
Copy Markdown

I have made things!

At runtime, SomeSerializer(many=True, ...) is swapped for a ListSerializer via many_init, but the stubs type it as the original serializer, so valid calls are rejected and downstream attributes lie about their types.

This adds a get_function_signature_hook on every registered serializer class that, when many=True is literally passed:

  • accepts the ListSerializer-only kwargs min_length and max_length;
  • rewrites the constructor's return type to ListSerializer[Collection[_IN]], extracting _IN by mapping the child serializer's instance to BaseSerializer in its MRO.

@federicobond
federicobond force-pushed the serializer-many-list-kwargs branch from b80ed88 to 8622fcc Compare April 18, 2026 17:27
@intgr

intgr commented May 11, 2026

Copy link
Copy Markdown
Contributor

Thanks! Sorry for the long delay in responding.

This is a known issue, also documented at #827

Ideally, it would also be possible to express this with an overload of __new__() -> ListSerializer return type.

Problem is, right now mypy constrains the __new__ return type to be a subclass of Self. But there's an open issue to relax this constraint on mypy, with lots of users requesting it. I suspect mypy upstream would accept to change it:

I'd prefer to avoid maintaining a mypy plugin if possible. Would you be up to implementing this in mypy instead?

@intgr intgr self-assigned this May 11, 2026
@federicobond

Copy link
Copy Markdown
Author

Will take a look and see what I can do!

@intgr

intgr commented May 12, 2026

Copy link
Copy Markdown
Contributor

Great, thanks. If you see any reason why it wouldn't work then I can reconsider

@intgr

intgr commented May 28, 2026

Copy link
Copy Markdown
Contributor

@federicobond Not sure if you're aware, the blocker was solved in mypy: python/mypy#21441

@federicobond

Copy link
Copy Markdown
Author

Amazing. I was not aware!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants