Skip to content

Add module keyword argument to typing.TypeAliasType #149132

@ericmarkmartin

Description

@ericmarkmartin

Feature or enhancement

Proposal:

Add an optional keyword-only module argument to typing.TypeAliasType, so that callers can override the __module__ attribute at construction time instead of relying on frame introspection.

Note that while I have posted this idea on Discourse (see linked thread), I haven't gotten any replies. I optimistically take this as the proposal being minor and uncontroversial.

Motivation

typing.TypeAliasType currently derives __module__ from a frame walk. This is unsuitable when constructing TypeAliasType objects inside exec, from C, or with a factory helper. In such cases caller() returns None or the wrong module.

There is currently no way to fix this after the fact, because __module__ is read-only:

>>> from typing import TypeAliasType
>>> ta = TypeAliasType("A", int)
>>> ta.__module__ = "x"
AttributeError: attribute '__module__' of 'typing.TypeAliasType' objects is not writable

Meanwhile there are consumers that rely on __module__, such as IDE go-to-definition or introspection-based stub generation (e.g. with f"{alias.__module__}.{alias.__qualname__}"). Such tools have no good recourse when __module__ is wrong.

Adding a __module__ kwarg to the TypeAliasType constructor is an easy, backward-compatible way to address this.
collections.namedtuple and enum.Enum expose such a kwarg and thus serve as precedent. Admittedly, the motivations for this kwarg in namedtuple and Enum seem to have more to do with pickling, which is not a use-case of especial import for TypeAliasType (though certainly one can pickle a TypeAliasType).

API

The new TypeAliasType constructor signature would be

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

module=None (default or explicit) preserves today's behavior. Any other value is stored verbatim with no validation, matching the namedtuple and enum APIs. Note that I don't object to adding validation here, but figured I'd start off by proposing something most consistent with the precedential APIs.

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/adding-a-module-keyword-argument-to-typing-typealiastype/107087

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-typingtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions