Skip to content

re.split has seemingly unnecessary Anys #7940

Closed

Description

@GrantGryczan

I would think that the | Anys in the following four return types should be removed.

def split(self: Pattern[str], string: str, maxsplit: int = ...) -> list[str | Any]: ...

def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = ...) -> list[bytes | Any]: ...

def split(pattern: str | Pattern[str], string: str, maxsplit: int = ..., flags: _FlagsType = ...) -> list[str | Any]: ...

) -> list[bytes | Any]: ...

Activity

  1. JelleZijlstra commented on May 24, 2022

    @JelleZijlstra
    Member

    They're there because the list entries can be None:

    In [6]: re.split(r"(a)|(b)", "canada")
    Out[6]: ['c', 'a', None, 'n', 'a', None, 'd', 'a', None, '']
    

    Though this behavior doesn't appear to be documented: https://docs.python.org/3.10/library/re.html#re.split

  2. GrantGryczan commented on May 25, 2022

    @GrantGryczan
    Author

    Huh, alright then. Strange that it isn't documented.

  3. GrantGryczan commented on May 25, 2022

    @GrantGryczan
    Author

    Actually, would it be a bad idea to replace the Anys with None in that case? Otherwise, in my use case, I'll have to cast the return value as list[str | None] myself.

  4. JukkaL commented on May 25, 2022

    @JukkaL
    Contributor

    Having None in the return value would likely cause many false positives, since often the caller can predict that there will only be strings. That's why the | Any was there in the first place instead of | None.

    It would be good to add a comment explaining the Any types, as otherwise this will continue to cause confusion.

  5. AlexWaygood commented on May 25, 2022

    @AlexWaygood
    Member

    It would be good to add a comment explaining the Any types, as otherwise this will continue to cause confusion.

    @srittau has proposed #7870 to tackle this problem in a more general way; we're currently bikeshedding debating the appropriate name for the feature.

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

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions