Skip to content

Make TypeAliasType __module__ attribute writable #149171

@ericmarkmartin

Description

@ericmarkmartin

Feature or enhancement

Proposal:

Make the __module__ attribute on TypeAliasType writable. This allows users to overwrite the attribute when frame introspection gets it wrong.

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 frame introspection 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.__name__}"). Such tools have no good recourse when __module__ is wrong.

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