-
-
Notifications
You must be signed in to change notification settings - Fork 224
Consider making Serializer
generic in t.AnyStr
for type checking to avoid overly ambiguous return types
#347
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Any suggestion on how to handle the fact that |
@davidism That's what the suggested overloads are for, the first overload will be matched when only the By now PEP-696 is already pretty well supported however, so you can also provide a default type on the |
I can take a stab at a PR, if the example on its own isn't illustrative enough. |
Most use cases do not involve providing a |
I just opened a PR if you want to review it: #374 |
Thanks, the override hint was what I needed, I did what I suggested and now mypy and pyright know the default is |
Uh oh!
There was an error while loading. Please reload this page.
Currently
Serializer.dumps
has an ambiguous return type (str | bytes
) due to how the Serializer determines its own return type in__init__
however for some of the derived classes such asURLSafeSerializer
we know statically that the return type will bestr
and notbytes
.If
Serializer
were generic we could perform this type narrowing when we inherit fromSerializer
by instead inheriting fromSerializer[str]
. That way we don't need totype:ignore
orassert isinstance(a, str)
everywhere we use aURLSafeSerializer
and correctly expect to get astr
back fromdumps
.If you wanted to be a bit more fancy you could even define a generic Protocol for the custom serializer that's passed in
__init__
(rather than useAny
) and create overloads to return the correct Serializer type, i.e. ifdumps
on the Serializer that's passed in returns bytes, then it will returnSerializer[bytes]
, the default withNone
can then returnSerializer[str]
.i.e. something like this: (it would require a bit more care due to the order of arguments, to properly match every possible case, but the basic idea should come across)
Environment:
The text was updated successfully, but these errors were encountered: