Skip to content

gh-137065: Unmerge types.UnionType and typing.Union #137069

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Doc/deprecations/pending-removal-in-future.rst
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ although there is currently no date scheduled for their removal.
* :class:`typing.Text` (:gh:`92332`).

* The internal class ``typing._UnionGenericAlias`` is no longer used to implement
:class:`typing.Union`. To preserve compatibility with users using this private
:data:`typing.Union`. To preserve compatibility with users using this private
class, a compatibility shim will be provided until at least Python 3.17. (Contributed by
Jelle Zijlstra in :gh:`105499`.)

Expand Down
4 changes: 2 additions & 2 deletions Doc/library/functools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ The :mod:`functools` module defines the following functions:
... for i, elem in enumerate(arg):
... print(i, elem)

:class:`typing.Union` can also be used::
:data:`typing.Union` can also be used::

>>> @fun.register
... def _(arg: int | float, verbose=False):
Expand Down Expand Up @@ -663,7 +663,7 @@ The :mod:`functools` module defines the following functions:

.. versionchanged:: 3.11
The :func:`~singledispatch.register` attribute now supports
:class:`typing.Union` as a type annotation.
:data:`typing.Union` as a type annotation.


.. class:: singledispatchmethod(func)
Expand Down
19 changes: 7 additions & 12 deletions Doc/library/stdtypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5573,7 +5573,7 @@ Union Type
A union object holds the value of the ``|`` (bitwise or) operation on
multiple :ref:`type objects <bltin-type-objects>`. These types are intended
primarily for :term:`type annotations <annotation>`. The union type expression
enables cleaner type hinting syntax compared to subscripting :class:`typing.Union`.
enables cleaner type hinting syntax compared to subscripting :data:`typing.Union`.

.. describe:: X | Y | ...

Expand Down Expand Up @@ -5609,7 +5609,7 @@ enables cleaner type hinting syntax compared to subscripting :class:`typing.Unio

int | str == str | int

* It creates instances of :class:`typing.Union`::
* It creates instances of :class:`types.UnionType`::

int | str == typing.Union[int, str]
type(int | str) is typing.Union
Expand Down Expand Up @@ -5638,15 +5638,15 @@ enables cleaner type hinting syntax compared to subscripting :class:`typing.Unio
TypeError: isinstance() argument 2 cannot be a parameterized generic

The user-exposed type for the union object can be accessed from
:class:`typing.Union` and used for :func:`isinstance` checks::
:class:`types.UnionType` and used for :func:`isinstance` checks::

>>> import typing
>>> isinstance(int | str, typing.Union)
>>> import types
>>> isinstance(int | str, types.UnionType)
True
>>> typing.Union()
>>> types.UnionType()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create 'typing.Union' instances
TypeError: cannot create 'types.UnionType' instances

.. note::
The :meth:`!__or__` method for type objects was added to support the syntax
Expand All @@ -5673,11 +5673,6 @@ The user-exposed type for the union object can be accessed from

.. versionadded:: 3.10

.. versionchanged:: 3.14

Union objects are now instances of :class:`typing.Union`. Previously, they were instances
of :class:`types.UnionType`, which remains an alias for :class:`typing.Union`.


.. _typesother:

Expand Down
4 changes: 3 additions & 1 deletion Doc/library/types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,9 @@ Standard names are defined for the following types:

.. versionchanged:: 3.14

This is now an alias for :class:`typing.Union`.
Added read-only attributes :attr:`!__name__`, :attr:`!__qualname__`
and :attr:`!__origin__`.


.. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)

Expand Down
10 changes: 5 additions & 5 deletions Doc/library/typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1086,7 +1086,7 @@ Special forms
These can be used as types in annotations. They all support subscription using
``[]``, but each has a unique syntax.

.. class:: Union
.. data:: Union

Union type; ``Union[X, Y]`` is equivalent to ``X | Y`` and means either X or Y.

Expand Down Expand Up @@ -1128,10 +1128,10 @@ These can be used as types in annotations. They all support subscription using
:ref:`union type expressions<types-union>`.

.. versionchanged:: 3.14
:class:`types.UnionType` is now an alias for :class:`Union`, and both
``Union[int, str]`` and ``int | str`` create instances of the same class.
To check whether an object is a ``Union`` at runtime, use
``isinstance(obj, Union)``. For compatibility with earlier versions of
Both ``Union[int, str]`` and ``int | str`` now create instances of
the same class, :class:`types.UnionType`.
To check whether an object is a union at runtime, use
``isinstance(obj, types.UnionType)``. For compatibility with earlier versions of
Python, use
``get_origin(obj) is typing.Union or get_origin(obj) is types.UnionType``.

Expand Down
4 changes: 2 additions & 2 deletions Doc/whatsnew/3.10.rst
Original file line number Diff line number Diff line change
Expand Up @@ -723,10 +723,10 @@ PEP 604: New Type Union Operator

A new type union operator was introduced which enables the syntax ``X | Y``.
This provides a cleaner way of expressing 'either type X or type Y' instead of
using :class:`typing.Union`, especially in type hints.
using :data:`typing.Union`, especially in type hints.

In previous versions of Python, to apply a type hint for functions accepting
arguments of multiple types, :class:`typing.Union` was used::
arguments of multiple types, :data:`typing.Union` was used::

def square(number: Union[int, float]) -> Union[int, float]:
return number ** 2
Expand Down
2 changes: 1 addition & 1 deletion Doc/whatsnew/3.11.rst
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,7 @@ functools
---------

* :func:`functools.singledispatch` now supports :class:`types.UnionType`
and :class:`typing.Union` as annotations to the dispatch argument.::
and :data:`typing.Union` as annotations to the dispatch argument.::

>>> from functools import singledispatch
>>> @singledispatch
Expand Down
34 changes: 9 additions & 25 deletions Doc/whatsnew/3.14.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2089,8 +2089,8 @@ turtle
types
-----

* :class:`types.UnionType` is now an alias for :class:`typing.Union`.
See :ref:`below <whatsnew314-typing-union>` for more details.
* Add read-only attributes :attr:`!__name__`, :attr:`!__qualname__` and
:attr:`!__origin__` for :class:`types.UnionType` instances.
(Contributed by Jelle Zijlstra in :gh:`105499`.)


Expand All @@ -2099,38 +2099,22 @@ typing

.. _whatsnew314-typing-union:

* :class:`types.UnionType` and :class:`typing.Union` are now aliases for each other,
meaning that both old-style unions (created with ``Union[int, str]``) and new-style
unions (``int | str``) now create instances of the same runtime type. This unifies
* Both old-style unions (created with ``Union[int, str]``) and new-style
unions (``int | str``) now create instances of the same runtime type,
:class:`types.UnionType`. This unifies
the behavior between the two syntaxes, but leads to some differences in behavior that
may affect users who introspect types at runtime:

- Both syntaxes for creating a union now produce the same string representation in
``repr()``. For example, ``repr(Union[int, str])``
is now ``"int | str"`` instead of ``"typing.Union[int, str]"``.
- Unions created using the old syntax are no longer cached. Previously, running
``Union[int, str]`` multiple times would return the same object
(``Union[int, str] is Union[int, str]`` would be ``True``), but now it will
return two different objects. Users should use ``==`` to compare unions for equality, not
``is``. New-style unions have never been cached this way.
This change could increase memory usage for some programs that use a large number of
unions created by subscripting ``typing.Union``. However, several factors offset this cost:
unions used in annotations are no longer evaluated by default in Python 3.14
because of :pep:`649`; an instance of :class:`types.UnionType` is
itself much smaller than the object returned by ``Union[]`` was on prior Python
versions; and removing the cache also saves some space. It is therefore
unlikely that this change will cause a significant increase in memory usage for most
users.
- Previously, old-style unions were implemented using the private class
``typing._UnionGenericAlias``. This class is no longer needed for the implementation,
but it has been retained for backward compatibility, with removal scheduled for Python
3.17. Users should use documented introspection helpers like :func:`typing.get_origin`
and :func:`typing.get_args` instead of relying on private implementation details.
- It is now possible to use :class:`typing.Union` itself in :func:`isinstance` checks.
For example, ``isinstance(int | str, typing.Union)`` will return ``True``; previously
this raised :exc:`TypeError`.
- The ``__args__`` attribute of :class:`typing.Union` objects is no longer writable.
- It is no longer possible to set any attributes on :class:`typing.Union` objects.
- The ``__args__`` attribute of :data:`typing.Union` objects is no longer writable.
- It is no longer possible to set any attributes on the :data:`typing.Union` objects.
This only ever worked for dunder attributes on previous versions, was never
documented to work, and was subtly broken in many cases.

Expand Down Expand Up @@ -2782,8 +2766,8 @@ Changes in the Python API
This temporary change affects other threads.
(Contributed by Serhiy Storchaka in :gh:`69998`.)

* :class:`types.UnionType` is now an alias for :class:`typing.Union`,
causing changes in some behaviors.
* Subscription of :data:`typing.Union` now returns a :class:`types.UnionType`
instance, causing changes in some behaviors.
See :ref:`above <whatsnew314-typing-union>` for more details.
(Contributed by Jelle Zijlstra in :gh:`105499`.)

Expand Down
5 changes: 3 additions & 2 deletions Lib/annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import keyword
import sys
import types
from _typing import _make_union

__all__ = [
"Format",
Expand Down Expand Up @@ -292,10 +293,10 @@ def __hash__(self):
))

def __or__(self, other):
return types.UnionType[self, other]
return _make_union(self, other)

def __ror__(self, other):
return types.UnionType[other, self]
return _make_union(other, self)

def __repr__(self):
extra = []
Expand Down
3 changes: 2 additions & 1 deletion Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1333,7 +1333,8 @@ def getargvalues(frame):
def formatannotation(annotation, base_module=None, *, quote_annotation_strings=True):
if not quote_annotation_strings and isinstance(annotation, str):
return annotation
if getattr(annotation, '__module__', None) == 'typing':
if (isinstance(annotation, types.UnionType)
or getattr(annotation, '__module__', None) == 'typing'):
def repl(match):
text = match.group()
return text.removeprefix('typing.')
Expand Down
3 changes: 2 additions & 1 deletion Lib/test/test_annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import itertools
import pickle
from string.templatelib import Template
import types
import typing
import unittest
from annotationlib import (
Expand Down Expand Up @@ -137,7 +138,7 @@ class UnionForwardrefs:
str | int,
)
union = annos["union"]
self.assertIsInstance(union, Union)
self.assertIsInstance(union, types.UnionType)
arg1, arg2 = typing.get_args(union)
self.assertIs(arg1, str)
self.assertEqual(
Expand Down
16 changes: 8 additions & 8 deletions Lib/test/test_pydoc/test_pydoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1444,19 +1444,19 @@ def test_generic_alias(self):
self.assertIn(list.__doc__.strip().splitlines()[0], doc)

def test_union_type(self):
self.assertEqual(pydoc.describe(typing.Union[int, str]), 'Union')
self.assertEqual(pydoc.describe(typing.Union[int, str]), 'UnionType')
doc = pydoc.render_doc(typing.Union[int, str], renderer=pydoc.plaintext)
self.assertIn('Union in module typing', doc)
self.assertIn('class Union(builtins.object)', doc)
self.assertIn('UnionType in module types', doc)
self.assertIn('UnionType = typing.Union', doc)
if typing.Union.__doc__:
self.assertIn(typing.Union.__doc__.strip().splitlines()[0], doc)

self.assertEqual(pydoc.describe(int | str), 'Union')
self.assertEqual(pydoc.describe(int | str), 'UnionType')
doc = pydoc.render_doc(int | str, renderer=pydoc.plaintext)
self.assertIn('Union in module typing', doc)
self.assertIn('class Union(builtins.object)', doc)
if not MISSING_C_DOCSTRINGS:
self.assertIn(types.UnionType.__doc__.strip().splitlines()[0], doc)
self.assertIn('UnionType in module types', doc)
self.assertIn('UnionType = typing.Union', doc)
if typing.Union.__doc__:
self.assertIn(typing.Union.__doc__.strip().splitlines()[0], doc)

def test_special_form(self):
self.assertEqual(pydoc.describe(typing.NoReturn), '_SpecialForm')
Expand Down
6 changes: 3 additions & 3 deletions Lib/test/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -1161,9 +1161,9 @@ def test_or_type_operator_reference_cycle(self):

def test_instantiation(self):
check_disallow_instantiation(self, types.UnionType)
self.assertIs(int, types.UnionType[int])
self.assertIs(int, types.UnionType[int, int])
self.assertEqual(int | str, types.UnionType[int, str])
self.assertIs(int, typing.Union[int])
self.assertIs(int, typing.Union[int, int])
self.assertEqual(int | str, typing.Union[int, str])

for obj in (
int | typing.ForwardRef("str"),
Expand Down
Loading
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy