Coming soon - Get a detailed view of why an account is flagged as spam!
view details

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.

1
Dynamic Annotated types?
Post Body

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?

Author
Account Strength
100%
Account Age
13 years
Verified Email
Yes
Verified Flair
No
Total Karma
140,975
Link Karma
2,184
Comment Karma
137,443
Profile updated: 1 week ago
Posts updated: 6 months ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
1 year ago