Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork33.7k
Description
Bug report
Bug description:
While looking into#125618 I ran into this case.
Using the union syntax gives aForwardRef that can't be evaluated as the class that can be evaluated gets converted into itsrepr viaast.Constant. Using thetyping.Union class however gives a proper union object where only the undefined value is a forwardref.
str | undefined->ForwardRef("<class 'str'> | undefined")Union[str, undefined]->str | ForwardRef("undefined")
Example:
fromannotationlibimportget_annotations,FormatfromtypingimportUnionclassDifferentUnions:attrib:str|undefinedother_attrib:Union[str,undefined]different_unions=get_annotations(DifferentUnions,format=Format.FORWARDREF)print(different_unions)
Formatted Output:
{'attrib':ForwardRef("<class 'str'> | undefined",is_class=True,owner=<class'__main__.DifferentUnions'>),'other_attrib':str|ForwardRef('undefined',is_class=True,owner=<class'__main__.DifferentUnions'>)}One possible solution to this is to add acreate_unions attribute to the_StringifierDict. If this isTrue then the__or__ and__ror__ methods should createtypes.UnionType instances instead of calling__make_new. This isFalse forFormat.STRING in order to keepa | b in the reproduction in that case.
I already have a branch with this approach so I can make a PR.
Doing this will break the currenttest_nonexistent_attribute ForwardRef test assome | obj would evaluate toForwardRef('some') | ForwardRef('obj') instead ofForwardRef('some | obj') but I think this is probably correct and the test should be changed.
CPython versions tested on:
CPython main branch
Operating systems tested on:
No response