You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee=Noneclosed_at=<Date2021-10-16.15:43:32.751>created_at=<Date2021-10-15.16:37:31.685>labels= ['type-bug', '3.11']
title='ForwardRef does not support | operator'updated_at=<Date2021-10-16.15:43:32.750>user='https://github.com/partiallyderived'
Not positive this is a bug, but it seems like ForwardRef should support the pipe (|) operator for indicating Unions in Python 3.10:
Python 3.10.0 (default, Oct 4 2021, 22:09:55) [GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from typing import ForwardRef
>>> ForwardRef('asdf') | ForwardRef('fdsa')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'ForwardRef' and 'ForwardRef'
>>> int|str
int | str
>>>
Activity
partiallyderived commentedon Oct 15, 2021
Not positive this is a bug, but it seems like ForwardRef should support the pipe (|) operator for indicating Unions in Python 3.10:
corona10 commentedon Oct 16, 2021
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -719,6 +719,12 @@ def __eq__(self, other):
def __hash__(self):
return hash(self.__forward_arg__)
+ def __or__(self, other):
+ return Union[self, other]
+
+ def __ror__(self, other):
+ return Union[other, self]
+
def __repr__(self):
return f'ForwardRef({self.__forward_arg__!r})'
This can be easily fixed, but I am waiting for guido and ken to check whether this is an intentioned operation.
gvanrossum commentedon Oct 16, 2021
I suppose this is useful for programs that use runtime annotations (e.g. pydantic?). I don’t mind adding this.
Fidget-Spinner commentedon Oct 16, 2021
ForwardRef is for internal use, and writing ForwardRef('fdsa') is discouraged, as the docs say:
This class should not be instantiated by a user.
However, I don't see any cons from adding union support, so let's do it!
Note that a workaround exists for OP's example. But it may not be sufficient for complex runtime libraries:
corona10 commentedon Oct 16, 2021
New changeset 15ad52f by Dong-hee Na in branch 'main':
bpo-45489: Update ForwardRef to support | operator. (GH-28991)
15ad52f
corona10 commentedon Oct 16, 2021
@guido
Do we need to create a backport for 3.10?
Ken and I are waiting for your comment :)
#28991 (comment)
gvanrossum commentedon Oct 16, 2021
No. :-)
Fidget-Spinner commentedon Oct 16, 2021
Thanks @corona10 for the patch.
@bobbeyreese
The new behavior is available in 3.11 and up. 3.10.x won't be supporting the | operator.