PEP 827: Type Manipulation

That would definitely be a reasonable type for this case. The trickier case would be something like:

type Partial[T] = typing.NewProtocol[
    *[
        typing.Member[p.name, p.type | None, p.quals]
        for p in typing.Iter[typing.Attrs[T]]
    ]
]

or something that does even more nontrivial computations in there.

I guess the crux of it would be that typing.NewProtocol[*tuple[Member[Any, Typ]]] would need to be understood as creating a protocol that has any names for members but all with type Typ. (Which can be modeled in the current system with a __getattr__, so it’s not quite a new notion…)

I think this will require a bit more thought to figure out if we can make those semantics work right overall, but I now think maybe we can. We’ll also need to decide if that’s what we want.

3 Likes

I would love to be able to write the machinery to do something like:

from typing import Self, Unpack
import kwconf


class MyConfig(kwconf.Config):
    host: str = kwconf.Value("localhost")
    port: int = kwconf.Value(8000)
    debug: bool = kwconf.Flag(False)

    @classmethod
    def cli(
        cls, argv=None,
        **kwargs: Unpack[Self.TypedDict],
    ) -> Self:
        ...

For GitHub - Erotemic/kwconf: A revised version of scriptconfig · GitHub

So the dataclass-like definition of the CLI can inform the kwargs the cli classmethod is able to accept. Hoping this PEP can get accepted.

1 Like

Hm, is it? My theory was that it would always update the decorated class

Took me a while to figure out what we were even talking about here :slight_smile: . It’s the UpdateClass construct, which I understand you’d use like this:

def make_awesome[T: type](cls: T) -> UpdateClass[Member[Literal["awesome"], Literal[True], Never, Literal[True], T]]:  # hope I got that right
    cls.awesome = True
    return cls

@make_awesome
class Spam: pass

My contention is that the return type of this decorator should have some way to indicate which class UpdateClass is updating; it’s weird for it to implicitly affect the first parameter. It also makes it so you can’t say what the function returns any more.

Currently it’s equivalent to GetMember[T, S].type, except that it is tolerant to S not existing on the type (produces Never); maybe it would be more useful to have it because like access on an instance, though?

I’d be curious about thoughts on this.

There have been some important changes to the PEP; here are some of the biggest:

To expand a bit on the changes downstream of PEP 849:

  • Get rid of the lambda in GenericCallable.
  • Get rid of runtime evaluation hooks
  • Get rid of Bool and Iter, which makes comprehensions look a lot nicer

Depending on that also gives a decent answer for how tools can consume these types without evaluating them at all.

1 Like

Yeah, that ought to work.

Yeah I think we’d want to support that.

A quick note (that the PEP authors could quote to the SC :slight_smile: ) that, while I originally found this proposal unwieldy, I am happy about the changes since then and would like to have it implemented so I can use it.

5 Likes

Yeah, OK: PEP 827: Make UpdateClass take the class to update as an argument by msullivan · Pull Request #5184 · python/peps · GitHub makes this change

@Jelle @carljm Following up on an offline discussion in person from last week about FromUnion:

I think that probably we should specify that the union should be simplified, which is what typescript does for conditional types.

The rationale for including it is that it is needed to implement things like Exclude and Extract, and if the user wants to lift some operation over a union. Whether lifting an operation over unions is actually a sensible thing to do depends on the operation.

In typescript, conditional types are lifted over unions by default, which is honestly also kind of ad-hoc, though I’d guess it’s the more useful thing more often than not? I don’t think that it is really an option for us, so if we want to support that, we need something more explicit.

PEP 827: Minor updates by msullivan · Pull Request #5198 · python/peps · GitHub incorporates some of this discussion into the PEP.

For ordering, I note that depending on the ordering of FromUnion is unstable and shouldn’t be relied on; if we really hate that, we could actually have a requirement of only being able to use union iteration to produce unions.

(In typescript it is actually possible to extract the order of the union by doing some horrific hacks involving the interpretation of an intersection as an orderloaded function allowing you to extract the last element of an intersection.)

‘GetMemberType’ should give the declared type, not the instance or class access type. The PEP’s own ‘select’ example depends on this since ‘ConvertField’ pulls ‘T’ out of ‘Property[T]’. If ‘Property’ were a real descriptor like SQLAlchemy’s ‘Mapped[T]’, which gives ‘T’ from an instance and ‘InstrumentedAttribute[T]’ from the class, neither would have a ‘Property[T]’ to extract ‘T’ from.

Well, if we made GetMemberType do the full descriptor protocol, then we’d have to update this to do GetMember[...].type or some such. But good catch that the current example probably depends on current behavior.

Makes sense, ‘GetMember[…].type’ covers that case.

Separately, on ‘UpdateClass’: I maintain a library that combines SQLAlchemy and Pydantic, where users write plain annotations and the model turns them into descriptors (background in this thread). Here is that transform in the current spelling. I ran it on the PoC (commit ‘5e9ae8d’) in the old spelling, because with ‘UpdateClass[T, …]’ the PoC leaves the class unchanged:

# Column[T] and Relationship[T] are descriptors: Self on the class, T on instances.
# Column.__set__ accepts T | Expression.
# relationship is an InitField subclass with kind: Literal["relationship"].
type Descriptor[Type, Init] = (
    Type
    if typing.IsAssignable[Type, Column[Any] | Relationship[Any]]
    else Relationship[Type]
    if typing.IsAssignable[Literal["relationship"], typing.GetMemberType[Init, Literal["kind"]]]
    else Column[Type]
)


class Model(metaclass=ModelMeta):  # ModelMeta uses dataclass_transform
    def __init_subclass__[T](cls: type[T]) -> typing.UpdateClass[
        T,
        *[
            typing.Member[p.name, Descriptor[p.type, p.init], p.quals, p.init]
            for p in typing.Attrs[T]
            if not typing.IsAssignable[Literal["ClassVar"], p.quals]
        ],
    ]: ...


class Parent(Model):
    memo: str | None = None
    children: list[Child] = relationship(default=[])


class Explicit(Model):
    count: Column[int] = Column()


reveal_type(Parent.memo)              # Column[str | None]
reveal_type(Parent().memo)            # str | None
reveal_type(Parent.memo == "refund")  # Expression
reveal_type(Parent.children)          # Relationship[list[Child]]
reveal_type(Parent.__init__)          # def (self, *, memo: str | None = ..., children: list[Child] = ...)
reveal_type(Explicit.__init__)        # def (self, *, count: int | Expression = ...)

The part I couldn’t settle is how ‘UpdateClass’ combines with ‘dataclass_transform’. For members that ‘UpdateClass’ replaced, the synthesized ‘init’ keeps the declared type (‘memo: str | None’), while ‘parent.memo = …’ goes through ‘Column.set’ and accepts ‘str | None | Expression’. For a field annotated with the descriptor directly, the PoC takes the parameter type from ‘set’ (‘count: int | Expression’), as mypy, pyright and ty do. Should the ‘init’ that ‘dataclass_transform’ synthesizes be computed from the members after ‘UpdateClass’ is applied? Or should libraries build ‘init’ themselves, as the PEP’s ‘InitFnType’ example does, and reimplement ‘KW_ONLY’, ‘init=False’ and aliases at the type level?

Yeah, good question. I think my hope is that libraries would do it themselves and dataclass_transform can be mostly ignored, but that might not be the right approach.

As implemented, the mypy poc runs UpdateClass after dataclass_transform, but that’s kind of ad-hoc and not the result of any particular design. If people think that doing it the other way around is better then I think that should be doable also. (Though maybe slightly fiddly, since the mypy implementation of dataclass_transform is based on looking at the AST, not the types or symbol table.)

I’d argue for running ‘UpdateClass’ first. It matches runtime, where ‘init_subclass’ runs inside ‘type.new’, before a metaclass or class decorator builds ‘init’. It also makes ‘init’ treat a ‘memo’ that ‘UpdateClass’ turned into ‘Column[str | None]’ the same as a field annotated ‘count: Column[int]’ directly, where checkers already take the parameter type from ‘set’.

I had a look at some of the PEP, and have some preliminary feedback.


Python has a gradual type system, but at the heart of it is a fairly conventional static type system.

I wouldn’t Python’s type system conventional. Even if you ignore the gradual typing, it’s closer to a semantic subtyping type system by Frisch et al., which in type-theory literature is way less common than e.g. System F, Martin-Löf type theory (MLTT), or calculus of constructions (CoC). Many typing features that we consider “normal” in Python, such as Literal, overload, and even (non-discriminated) union types, aren’t as common as you might think.


In Python as a language, on the other hand, it is not unusual to perform complex metaprogramming, especially in libraries and frameworks. The type system typically cannot model metaprogramming.

I think you’re underestimating the power of Protocol.


To bridge the gap between metaprogramming and the type system, some libraries come with custom mypy plugins. […] The problem with this approach is that many typecheckers do not (and will not) have a plugin API, so having consistent typechecking across IDEs, CI, and tooling is not achievable.

Some other type-checkers are also special-casing specific libraries. For example Pyrefly has support for Django, Polars, Pytest, Pydantic, etc. So I wouldn’t say that plugins are the only way for type-checkers to add support the metaprogramming acrobatics that can’t be expressed within Python’s current type system.


Given the significant mismatch between the expressiveness of the Python language and its type system

The “significant mismatch” is a pretty bold claim that isn’t backed up here. In my experience, Python’s type system is actually very powerful, mostly thanks to overloading and structural typing. I wouldn’t be surprised if 90% of real-world Python code can already be accurately typed.


Prisma, a popular ORM for TypeScript

Maybe it’s just me, but I’ve never heard of Prisma. I think that an example of a Python library would be more helpful here. Since there’s already Pydantic (which I personally also don’t have much experience with) and dataclasses as examples (both of which have very similar use-cases), I’d suggest something outside of the “schema type” / ORM family of libraries.


A minor proposal that can probably be split off into a typing proposal without a PEP:
Supporting Unpack of typevars for **kwargs:

This always felt like something that “should just work”, so thanks for making it concrete. I also agree this we should try to address this separately, instead of piggybacking it onto this PEP.


Extended Callables

Functionally, I really like this, and I definitely have use-cases for it. But it’s extremely verbose, and to me it looks more like some low-level / AST-like syntax that’s not supposed to see the light of day. One of Python’s main selling polnt is in its readability, so I think we should be very careful not not sacrifice that for the sake of functionality. So personally, I don’t think that adding this in its current form is wise. A dedicated PEP just for this, with clean and intuitive syntax, would have my preference (easier said than done, of course).


Alright, it’s bedtime for me here, so that’s it for now :slight_smile:

2 Likes

Thank you!

I agree with you that it’s not strictly conventional, which is why there was an emphasized hedge word in front of it! I’m happy to strike that comment or soften it more. And I actually think that non-discriminated union types might be the least conventional of all the things you mentioned!


I agree that Python typing supports most Python code! I like Python typing. None of this is supposed to be an attack on Python typing, and I now worry that some of my language has come across that way, and if so I should adjust it.

But 90% leaves room for improvement, and I think it’s worth pursuing that.


I wasn’t really focusing on what type-checkers can do here, but what library authors can do, if they need


I’ll do some pondering on if there’s a good replacement example; the prisma-style one comes directly from the PEP authors’ personal experience though, which is part of why we chose it: at a now-defunct company, we wanted to build a nice query-builder for our database system and were never able to type it to our satisfaction.

(I also think that even though they all build on top of some kind of expanded schema type system, the @dataclass example, the FastAPI type transformation example, and the query builder example are all doing very different things.)

But here’s a fun less-dataclassy one that someone brought into a typing open space at the core dev sprint the other week: they have a function coerce that works like:

@coerce(path=pathlib.Path, limit=int)
def whatever(path: pathlib.Path, limit: int) -> None:
    ....

and produces a function that uses the callables passed to coerce to coerce arguments to the proper types. They use a mypy plugin to type this, but 827 could handle it.
(It can be done for up-to-N positional arguments using overloads already, though.)


I do agree that extended callables deserve their own, good, syntax! PEP 677 considered but decided against proposing that (PEP 677 – Callable Type Syntax | peps.python.org), and then of course the whole PEP got rejected anyway. I would really like to see 677 tried again and to include the extended syntax.

But even if we already had that, I’d still be proposing something like this AST-like extended callable syntax.

The problem is that for type manipulation PEP to be useful in many of the ways we want, we need to be able to construct basically arbitrary callable types by mapping over other types: consider implementing dataclasses, where we need to be able to produce a __init__ function that might have all four of positional-or-keyword, positional-or-keyword-with-default, keyword-only, and keyword-only-with-default, produced by inspecting the class definition.

This means supporting some kind of general “programmatic” way to create (and introspect) callables; this was the nicest thing we managed to come up with; I’d be happy if anybody has a suggestion for a nicer path.

TypeScript has much simpler function parameters, and is able to represent a function in the general case as an unpack of a tuple type. But Python has eight different kinds of function parameters, which makes this all harder.

(One tempting idea that doesn’t quite work is trying to treat them as an unpack of a *args tuple (or union of tuples, to account for defaults) and as an unpack of a **kwargs typed dict. This unfortunately doesn’t account for positional-or-keyword parameters.)

The fact that this extended callable syntax can also be used to manually write callable types (like we do in the example, maybe unwisely) has actually mostly seemed a disadvantage to me, because it is not at all the goal but always draws a lot of attention to the particular ergonomics of it.

An alternative approach to these “extended callables” would be to have NewProtocol specifically have a way to specify method signatures other than by giving a Callable for them. We didn’t do it that way because it felt kind of unnecessarily clunky. It would overall be pretty similar in effect but it would signal very strongly that the purpose is for use with NewProtocol. (It still would be possible to create a “standalone” callable by using NewProtocol to create a callback protocol.)

This might be too bikesheddy, but is it intentional that we reuse any/all but then introduce new special forms that have essentially the same meaning as other existing builtins? E.g. Length[...] seems identical to len(...) or GetMember[...] to getattr(...)? Having to remember which builtins can be used in typing contexts and which need to be spelled slightly differently seems confusing. Personally it feels like just reusing the existing builtins would be easier to teach and use (similar to how builtin container types were made subscriptable and replaced the List/Dict constructs).

6 Likes