This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
I'm using Pydantic to create a number of custom types with validation and serialization logic. They look like this:
MyType = Annotated[BackedType, myvalidator(arg), myserializer(arg), myschema(arg)]
where myvalidator
, myserializer
, myschema
return instances of BeforeValidator
, PlainSerializer
and GetPydanticSchema
respectively. That seems to be the preferred way to do it, ref documentation.
Now a lot of this is repetitive, so I would like to do something like this:
MyType = Annotated[BackedType, *everything_in_one(arg)]
But that's illegal syntax in a type parameter context: can't splat there. So I thought, since Annotated[BackedType, ...]
is equivalent to BackedType
in a type checking context, can I not do something like this?
def make_annotated(arg) -> Type[BackedType]:
return Annotated[BackedType, ...etc]
MyType = make_annotated(arg) # mypy understands that this is BackedType.
But I can't get this to type check. Apparently mypy thinks the return value from the function is just object
, and if I cast it, mypy claims that this is not valid as a type - nor does it work if i annotate it as a TypeAlias
(the expression is an invalid type alias).
Is there a way to make this sort of thing work?
Subreddit
Post Details
- Posted
- 1 year ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learnpython...