Skip to content

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

Closed as not planned
Closed as not planned
@john-dicarlo

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

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