Please consider delaying, or even rejecting, PEP 695

I’ll chime in a bit from the perspective of Pydantic.

I’ve reviewed the PEP and believe that not only will it not hurt runtime type checking but it seems like in general it would be of great benefit to runtime type checking, especially in combination with PEP 649. In brief:

  • TypeVar defaults help us because we need to do stuff at runtime in situations where they can’t be parametrized directly (def foo(x: MyModel[T]) for example). We currently use the TypeVar bound or Any, but a default would be more explicit.
  • The new generics syntax and associated scoping rules should make it easier to parametrize models. When someone does GenericModel[T1, T2][T2, int][str] and whatnot we have to trace that through that model, all sub models, etc. I think we mostly handle this now but there may be situations where re-using a TypeVar in multiple places makes it hard to keep track of things. Having more “unique” TypeVars would help.
  • We use to PEP 593 heavily to add runtime typing information without messing with static type checking, but you can’t name type aliases created this way. If you have Users = Annotated[List[User], MaxLen(10)] and use users: MyAlias in a FastAPI function you probably want the parameter to be called Users in your OpenAPI schema, but that name is lost at runtime.

While I personally like the new syntax a lot and would love to be able to upgrade non-library code to use it in a couple of months, I have to recognize that all of the points but the new generics syntax could be enabled without the syntax changes, and maybe even backported through typing-extensions. That’s a lot more interesting for Pydantic and it’s users because otherwise it wouldn’t benefit our users for years (if we have to wait for all Python versions to support these features) or at least require a lot of effort from us to support things on only some versions. TypeVar defaults are already available in typing-extensions. I think it should be possible to introduce the new TypeAlias class so that Foo = TypeAlias(Annotated[int, …], name=“MyInt”) can be understood by type checkers. And if Pydantic (and similar projects) can’t test out these new features or has little incentive to do so we loose valuable feedback (like I said above I read the PEP but it is indeed complex and I can’t promise we won’t encounter issues until we support and use it).

I won’t opine on delaying the PEP or not, I leave that to those more knowledgeable, but I can say that in general we are both supportive of the changes but are also in favor of exploring ways to get them without syntax changes to get users more immediate benefit and make implementation easier for us. I hope this can be explored even if the features ship in 3.12.

3 Likes