Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[3.14] annotationlib - Union '|' syntax and typing.Union[...] generate different forward references. #132805

Closed
Labels
3.14bugs and security fixesstdlibPython modules in the Lib dirtopic-typingtype-bugAn unexpected behavior, bug, or error
@DavidCEllis

Description

@DavidCEllis

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

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.14bugs and security fixesstdlibPython modules in the Lib dirtopic-typingtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp