Adding a `module=` keyword argument to `typing.TypeAliasType`

I want to propose adding a keyword module argument to TypeAliasType, which allows one to override the __module__ otherwise inferred by the constructor via the current interpreter frame. This is analogous to the module argument already supported by collections.namedtuple and enum.Enum.

The motivation is likewise getting __module__ right in cases like exec, constructing TypeAliasType objects from the C API, etc. While I’d be surprised if many people were depending on TypeAliasType objects’ __module__ for unpickling, it’s still helpful for use-cases like runtime-introspection-based stub generation or docgen.

Concretely, I’d propose making the interface

TypeAliasType(name, value, *, type_params=(), qualname=None, module=None)

With module omitted or explicitly passed as None, we’d infer __module__ exactly as today. With any other object passed, we’d pass that through directly to __module__ (regardless of whether it’s str, matching namedtuple and Enum behavior).

1 Like

Note that in Python 3.14, typing_extensions.TypeAliasType is currently a re-export of typing.TypeAliasType. In order to backport this feature to 3.14, we’d have to change this so that typing_extensions provides the Python-implemented TypeAliasType shim in 3.14 as well.

1 Like

We also don’t have this for TypeVar/ParamSpec/TypeVarTuple or for the recently added sentinel.

Should we make __module__ writable instead? That’s more in line with how classes/functions work.

1 Like

I had assumed that there was some reason things were read-only on TypeAliasType but if not I’d also be perfectly happy with a writable __module__.

If there’s agreement there I can write up a new issue/PR

Given that this is already how classes and typevars work, I think making the attribute writable makes sense.