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
converters: allow wrapping and passing self and fields #1267
base: main
Are you sure you want to change the base?
Conversation
34b85b8
to
f3bea45
Compare
Here are the changes for the next step. We need to make In = typing.TypeVar("In")
Out = typing.TypeVar("Out")
class Converter(typing.Generic[In, Out]):
"""
Stores a converter callable.
Allows for the wrapped converter to take additional arguments. The
arguments are passed in the order they are documented.
:param Callable converter: A callable that converts a value.
:param bool takes_self: Pass the partially initialized instance that is
being initialized as a positional argument. (default: `False`)
:param bool takes_field: Pass the field definition (an `Attribute`) into
the converter as a positional argument. (default: `False`)
.. versionadded:: 24.1.0
"""
__slots__ = (
"converter",
"takes_self",
"takes_field",
"_first_param_type",
"_global_name",
)
@typing.overload
def __init__(
self,
converter: typing.Callable[[In, AttrsInstance, typing.Any], Out],
*,
takes_self: typing.Literal[True] = ...,
takes_field: typing.Literal[True] = ...,
) -> None: ...
@typing.overload
def __init__(
self,
converter: typing.Callable[[In, typing.Any], Out],
*,
takes_field: typing.Literal[True] = ...,
) -> None: ...
@typing.overload
def __init__(
self,
converter: typing.Callable[[In, AttrsInstance], Out],
*,
takes_self: typing.Literal[True] = ...,
) -> None: ...
@typing.overload
def __init__(self, converter: typing.Callable[[In], Out]) -> None: ...
def __init__(self, converter, *, takes_self=False, takes_field=False):
self.converter = converter
self.takes_self = takes_self
self.takes_field = takes_field
self._first_param_type = _AnnotationExtractor(
converter
).get_first_param_type() Then, we change the type stubs for
I don't think this matters much since Mypy patches it. Optional additional step: we finally make Then, we implement support for this in the Mypy plugin. This should be pretty straightforward since |
This allows to wrap converters into classes and pass them the instance that is being initialized and the field for which the value is converted.
Things open:
init.md
fixes #404, fixes #709 (and probably more)
It will enable #240 if anyone still cares about it.