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
Is it possible to simplify registering user defined type? #56
Comments
Hey, @xbanke! Thanks for the input. What sort of custom user-type are you thinking of? Most any type is supported. The only real exceptions are recursive types (a class definition which takes an instance of the class itself) and Unions of multiple types (e.g., In the case of Unions, validation still works, but not conversion. Ex: from typing import Union
import typic
typic.validate(Union[int, str], b"foo")
#> typic.constraints.error.ConstraintValueError: Given value <b'foo'> fails constraints: (constraints=((type=int, nullable=False, coerce=False), (type=str, nullable=False, coerce=False)), nullable=False) I do think there's some room for improvement here, but I'd like to understand your use-case. |
Thanks for your quick reply @seandstewart . class Columns(typing.List[typic.Strict[str]]):
...
def coerce_columns(v) -> typing.List[typic.Strict[str]]:
if isinstance(v, str):
v = v.replace(',', ' ').replace(';', ' ').split()
return typic.transmute(typing.List[typic.Strict[str]], v)
def check_columns(ann) -> bool:
return ann is Columns
typic.register(coerce_columns, check_columns) As seen above, the code being splitted to several independent blocks and not straigthforward. I have temp solution by a decorator, still saying from functools imoprt wraps
import typic
def register(cls):
if not hasattr(cls, '__check__'):
@classmethod
def __check__(c, a):
return a is c
setattr(cls, '__check__', __check__)
typic.register(cls.__deserialize__, cls.__check__)
return cls And then we can rewrite the type @register
class Columns(typing.List[typic.Strict[str]]):
@classmethod
def __deserialize__(cls, v):
if isinstance(v, str):
v = v.replace(',', ' ').replace(';', ' ').split()
return typic.transmute(typing.List[typic.Strict[str]], v)
@classmethod
def __check__(cls, ann):
return ann is cls If possible, we can define some protocal which can handle this with out decorator. Thanks again. |
Thanks for the clarification and examples! This is super helpful, and pretty straightforward. The current registration system is a holdout from v1 and I’d love to make it more accessible. I’ll play with this and see what I can come up with! |
My pleasure. |
Description
Hi, I like typical and I think it's more lightweight than pydantic. But add user defined type by
typic.register
is something tedious or there's another convenient way I didn't found. If so, is it possible to simplify it like pydantic's__get_validators__
or some else?The text was updated successfully, but these errors were encountered: