Repository navigation
ForwardRef does not support | operator #89652
Description
Activity
partiallyderived commented
on Oct 15, 2021 partiallyderivedmannequinMannequinAuthorMore actionsNot 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 >>>
- added3.10 (EOL)end of lifeend of lifetype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
on Oct 15, 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.
I suppose this is useful for programs that use runtime annotations (e.g. pydantic?). I don’t mind adding this.
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:
ForwardRef('asdf | fdsa')
Do we need to create a backport for 3.10?
Ken and I are waiting for your comment :)
#28991 (comment)No. :-)
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.
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:
bugs.python.org fields: