Skip to content

Check for Match instance in Union[Match, str] #2282

Closed

Description

@mkurnikov

It's not clear for me, how should I use Pattern and Match type aliases to pick apart Union[Match, str].

It looks like Match type alias supports __subclasscheck__, but mypy used with

from typing import Match, Union

def process_consumed_issubclass(consumed: Union[Match, str]) -> str:
    if issubclass(type(consumed), Match):
        return consumed.group('res')

    return consumed

returns

test_mypy_match.py: note: In function "process_consumed_issubclass":
test_mypy_match.py:7: error: Some element of union has no attribute "group"
test_mypy_match.py:9: error: Incompatible return value type (got "Union[Match[Any], str]", expected "str")

Match.impl_type have type(stdlib_re.match('', '')), but isinstance check still doesn't work

def process_consumed_isinstance(consumed: Union[Match, str]) -> str:
    if isinstance(consumed, Match.impl_type):
        return consumed.group('res')

    return consumed
test_mypy_match.py: note: In function "process_consumed_isinstance":
test_mypy_match.py:13: error: Match[AnyStr] has no attribute "impl_type"
test_mypy_match.py:14: error: Some element of union has no attribute "group"
test_mypy_match.py:16: error: Incompatible return value type (got "Union[Match[Any], str]", expected "str")

mypy 0.4.5, cpython 3.5.2.

Activity

  1. gvanrossum commented on Oct 19, 2016

    @gvanrossum
    Member
  2. mkurnikov commented on Oct 19, 2016

    @mkurnikov
    ContributorAuthor

    Reverse check works fine, thanks. The issue was meant to be a bug report, feel free to close it, if it's irrelevant.

  3. gvanrossum commented on Oct 19, 2016

    @gvanrossum
    Member

    Hm, mypy doesn't understand issubclass(type(x), C) at all, and in general that should just be written using isinstance() (which works in mypy). But I understand that typing.py doesn't support this, even though it should. Can you file a bug about that in https://github.com/python/typing/issues ?

  4. mkurnikov commented on Oct 19, 2016

    @mkurnikov
    ContributorAuthor

    It looks like it's fixed in python/typing already with python/typing#283:
    https://github.com/python/typing/blame/master/src/typing.py#L312
    It just hasn't been released yet.

  5. gvanrossum commented on Oct 19, 2016

    @gvanrossum
    Member
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