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

Type-checking difference between re and regex modules #423

Open
mrabarnett opened this issue Aug 28, 2021 · 2 comments
Open

Type-checking difference between re and regex modules #423

mrabarnett opened this issue Aug 28, 2021 · 2 comments
Labels
enhancement New feature or request minor

Comments

@mrabarnett
Copy link
Owner

Original report by Anonymous.


The following code fails under both mypy and pyright:

import re
a: int = 1
m = re.match('foo', 'foobar')
if m:
  a = m[1]

As "str" is incompatible with "int". But the same does not happen for the regex module.

Is the solution something like

from typing import Match
m: Match[str] | None = regex.match(...)

or is there a better way to enable type checking here?

Thanks,

Rich

@mrabarnett
Copy link
Owner Author

Original comment by Matthew Barnett (Bitbucket: mrabarnett, GitHub: mrabarnett).


Python’s typing module knows about Match because re is the stdlib and the typing is defined in the typing module. You could look at how the types are defined for re and then try replicating that using regex.

@jpy-git
Copy link

jpy-git commented Dec 30, 2021

FYI I've added type stubs for the regex package to typeshed in this PR.

You can install them via pip install types-regex and then you'll be able to perform type analysis via mypy, pyright, etc:
image

Should also allow IDEs to provide detailed typing info:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request minor
Projects
None yet
Development

No branches or pull requests

2 participants