Skip to content
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

Open
wants to merge 13 commits into
base: main
Choose a base branch
from

Conversation

hynek
Copy link
Member

@hynek hynek commented Mar 17, 2024

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:

  • narrative docs in init.md
  • I'm not sure how to approach the typing side, since every attempt failed. I suspect due to a lack of Mypy plugin support. Can we somehow cheat our way here?

fixes #404, fixes #709 (and probably more)

It will enable #240 if anyone still cares about it.

@hynek hynek changed the title converters: allow wrapping & takes_self converters: allow wrapping and passing self and fields Mar 17, 2024
@hynek hynek force-pushed the 3-arg-converters branch 2 times, most recently from 34b85b8 to f3bea45 Compare March 18, 2024 14:34
@Tinche
Copy link
Member

Tinche commented Mar 24, 2024

Here are the changes for the next step.

We need to make Converter generic over the input and output types:

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 field to take:

converter: _ConverterType | Converter[Any, _T] | None = ...,

I don't think this matters much since Mypy patches it.

Optional additional step: we finally make attrs.Attribute generic at runtime. That will let us have better typing here (and is more correct in general).

Then, we implement support for this in the Mypy plugin. This should be pretty straightforward since Converter is nicely generic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Allow three-argument converters (like validators/on_setattr)
2 participants