Skip to content

Trying to iterate over typing.Union results in hang #92261

Description

@mrahtz

If you accidentally iterate over a Union, you get a hang:

from typing import Union
list(Union)
# ...hang

It looks like it's an infinite loop:

from typing import Union
for i in Union:
    print(i)
# 0, 1, 2, ...

As far as I can tell, this happens because typing.Union is implemented using typing._SpecialForm, and _SpecialForm is implemented using __getitem__ to support parameterisation like Union[int]. Unfortunately, because _SpecialForm doesn't implement __iter__, __getitem__ is also used for iteration - meaning that when trying to iterate, we effectively do Union[0], Union[1], etc.

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    on May 3, 2022
  2. JelleZijlstra commented on May 3, 2022

    @JelleZijlstra
    Member

    We should deprecate itertools.count because it's now redundant.

    More seriously, agree that we should disallow this.

  3. added a commit that references this issue on May 8, 2022
  4. mrahtz commented on May 8, 2022

    @mrahtz
    ContributorAuthor

    Fixed in 4739997.

  5. added a commit that references this issue on May 9, 2022
  6. added a commit that references this issue on May 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions