Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
john-dicarlo opened this issue Nov 9, 2023 · 2 comments
Closed

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

john-dicarlo opened this issue Nov 9, 2023 · 2 comments
Labels
bug mypy got something wrong

Comments

@john-dicarlo
Copy link

# 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

@john-dicarlo john-dicarlo added the bug mypy got something wrong label Nov 9, 2023
@hauntsaninja
Copy link
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.

@KotlinIsland
Copy link
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
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants