Skip to content

re.Match.group() output doesn't raise type error #16441

Closed as not planned
Closed as not planned

Description

@john-dicarlo
# example.py

import re

def foo(s: str) -> str:
   print(s)
   return s

m: re.Match[str] | None = re.match('(a)(b)?', 'a')

if m is not None:
   foo(None) # Argument 1 to "foo" has incompatible type "None"; expected "str"  [arg-type] # as expected
   
   reveal_type(m.group(2))  # Revealed type is "Union[builtins.str, Any]"
   foo(m.group(2)) # does not raise an [arg-type] error
   assert m.group(2) is None # passes
$ mypy --strict example.py 
example.py:12: error: Argument 1 to "foo" has incompatible type "None"; expected "str"  [arg-type]
example.py:14: note: Revealed type is "Union[builtins.str, Any]"
Found 1 error in 1 file (checked 1 source file)

Why doesn't m.group(2) raise an [arg-type] error here?

Your Environment

mypy 1.6.1 (compiled: yes)
Python 3.10.12

Activity

  1. hauntsaninja commented on Nov 12, 2023

    @hauntsaninja
    Collaborator

    See python/typeshed#9465 (comment) / python/typeshed#9482 (comment)

    There's a balance between false negatives (like this) and false positives. Typeshed aims to avoid false positives, which is why the return type uses a union containing Any. For many — maybe even most — regular expressions, group can't actually be None, so this is a good decision.

  2. KotlinIsland commented on Jan 18, 2024

    @KotlinIsland
    Contributor

    Basedmypy works correctly in these cases:

    import re
    
    s: str
    if m := re.match("a(b)?(c)", s):
        reveal_type(m.groups())  #  (str | None, str)
    
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

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions