Skip to content

Commit

Permalink
Add better type deduction for use-regex-pattern-methods
Browse files Browse the repository at this point in the history
  • Loading branch information
dosisod committed Feb 14, 2024
1 parent 835e7a8 commit aecd60a
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 10 deletions.
2 changes: 1 addition & 1 deletion docs/checks.md
Original file line number Diff line number Diff line change
Expand Up @@ -1872,7 +1872,7 @@ if x is None:

## FURB170: `use-regex-pattern-methods`

Categories: `readability` `regex`
Categories: `performance` `readability` `regex`

If you are passing a compiled regular expression to a regex function,
consider calling the regex method on the pattern itself: It is faster, and
Expand Down
14 changes: 5 additions & 9 deletions refurb/checks/regex/use_pattern_method.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from dataclasses import dataclass

from mypy.nodes import CallExpr, RefExpr, Var
from mypy.nodes import CallExpr, RefExpr

from refurb.checks.common import is_same_type
from refurb.checks.common import get_mypy_type, is_same_type
from refurb.error import Error


Expand Down Expand Up @@ -36,7 +36,7 @@ class ErrorInfo(Error):

name = "use-regex-pattern-methods"
code = 170
categories = ("readability", "regex")
categories = ("performance", "readability", "regex")


# This table represents the function calls that we will emit errors for. The
Expand Down Expand Up @@ -74,12 +74,8 @@ def check(node: CallExpr, errors: list[Error]) -> None:
if not arg_format:
return

match pattern:
case RefExpr(node=Var(type=ty)) if is_same_type(ty, "re.Pattern"):
pass

case _:
return
if not is_same_type(get_mypy_type(pattern), "re.Pattern"):
return

min_len = len([arg for arg in arg_format if arg is ...])

Expand Down
5 changes: 5 additions & 0 deletions test/data/err_170.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@

_ = search(PATTERN, "hello world")

class C:
p: re.Pattern

_ = re.sub(C().p, "hello world", "goodbye world")


# these should not

Expand Down
1 change: 1 addition & 0 deletions test/data/err_170.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ test/data/err_170.py:18:5 [FURB170]: Replace `re.sub(x, ..., ..., count=...)` wi
test/data/err_170.py:19:5 [FURB170]: Replace `re.subn(x, ..., ...)` with `x.subn(..., ...)`
test/data/err_170.py:20:5 [FURB170]: Replace `re.subn(x, ..., ..., count=...)` with `x.subn(..., ..., count=...)`
test/data/err_170.py:22:5 [FURB170]: Replace `re.search(x, ...)` with `x.search(...)`
test/data/err_170.py:27:5 [FURB170]: Replace `re.sub(x, ..., ...)` with `x.sub(..., ...)`

0 comments on commit aecd60a

Please sign in to comment.