This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Using typing.Union in isinstance checks
Type: enhancement Stage: resolved
Components: Versions:
process
Status: closed Resolution: out of date
Dependencies: Superseder:
Assigned To: Nosy List: jack__d, ktbarrett
Priority: normal Keywords:

Created on 2021-06-28 18:15 by ktbarrett, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg396658 - (view) Author: Kaleb Barrett (ktbarrett) Date: 2021-06-28 18:15
I have type aliases of Unions like so:

Request = Union[WriteRequest, ReadRequest]

I'd like to be able to use "Request" in an isinstance check rather than having to duplicate the information in a tuple to pass to the check. Currently I get:

TypeError: Subscripted generics cannot be used with class and instance checks

Seems like Unions could be used here interchangeably with tuples since they mean the same thing in this context. Of course this would only work if the element types are being capable of being used in isinstance checks.
msg396671 - (view) Author: Jack DeVries (jack__d) * Date: 2021-06-28 23:30
I think this already works unless you are using TypeVars::

    t = Union[str, int]

    isinstance(1, t)    # True
    isinstance('1', t)  # True

If you are using TypeVars, though, it cannot work:

    T = TypeVar('my_type')
    thing = Union[T, str]

    isinstance('hi', thing)  # Exception

This makes sense, because ``T`` is just a name, not related to an actual object.

Sorry if I'm missing something, because I did try the non-working example and my exception actually says, "issubclass() arg 2 must be a class, a tuple of classes, or a union." The exception makes sense, but its difference from yours might mean I'm doing something differently.
msg396694 - (view) Author: Kaleb Barrett (ktbarrett) Date: 2021-06-29 01:56
Ah, this was implemented for 3.10 as a part of PEP 604. https://www.python.org/dev/peps/pep-0604/#isinstance-and-issubclass.

Feel free to close.
History
Date User Action Args
2022-04-11 14:59:47adminsetgithub: 88695
2021-06-29 10:47:16eric.smithsetstatus: open -> closed
resolution: out of date
stage: resolved
2021-06-29 01:56:56ktbarrettsetmessages: + msg396694
2021-06-28 23:30:14jack__dsetnosy: + jack__d
messages: + msg396671
2021-06-28 18:15:36ktbarrettcreate