Feedback on PEP 712: Adding a "converter" parameter to dataclasses.field
Howdy folks! Most of PEP 712 is dedicated to working out the kinks and intricacies of typing when it comes to adding `converter` parameter, so I'd love to hear the typing-based feedback. Thanks!
FWIW here's a link to a current build of the PEP https://pep-previews--3095.org.readthedocs.build/pep-0712/ and the PR implementing it https://github.com/python/peps/pull/3095
I assume for generic functions, the return type is bound to the declared field type? So: def get_first(xs: list[T]) -> T: return xs[0] @dataclass class C: x: int = field(converter=get_first) C(x=["foo"]) # type error because T=int
Thanks for making this PEP Josh, I think it could be quite useful. One thing I'd like to see, as someone who hasn't actually needed this feature myself but can imagine use cases, is a few examples in the Motivation section illustrating some contexts where this would help. Something I'd suggest calling out is why a classmethod / staticmethod won't suffice. I tend to use that in my code when I need conversions, e.g. ``` @dataclasses.dataclass class Dataclass: x: TypeDerivedFromString @staticmethod def create(x: str): return Dataclass(x=DerivedFromString(x)) ``` I'm *guessing* that the motivation for not needing a creator method to do conversions is some combination of: - wanting to reduce verbosity - at least to me this argument may not land well, given a preference for explicit over implicit logic - wanting to be able to modify automated type-derived logic like serialization - my guess is that use cases like this will be very compelling Cheers, Steven Troxler
Pydantic doesn’t really work this way. What we really need is a way to tell dataclass_transform to look at some gross overloaded function for default conversion, something like: ``` @overload def pydantic_default_conversions(x: str, field: type[int]) -> int: … @overload def pydantic_default_conversions(x: int, field: type[str] -> NoReturn: … # not supported ``` Even then I’m not sure that would cover all cases since we support marking a class as “lax” (does these conversions) or “strict” (doesn’t do conversions)
participants (5)
-
Adrian Garcia Badaracco
-
James H-B
-
joshdcannon@gmail.com
-
Steven Troxler
-
Thomas Kehrenberg