Skip to content

Commit 8afa606

Browse files
committed
Replace globals() dispatch with explicit table in similarity (Codacy Semgrep)
1 parent d09debc commit 8afa606

1 file changed

Lines changed: 10 additions & 4 deletions

File tree

je_auto_control/utils/text_similarity/text_similarity.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,16 +134,22 @@ def dice(a: str, b: str, *, n: int = 2) -> float:
134134
return 2 * len(set_a & set_b) / total if total else 1.0
135135

136136

137+
_SIMILARITY_METRICS = {"jaro": jaro, "jaro_winkler": jaro_winkler,
138+
"jaccard": jaccard, "dice": dice}
139+
_DISTANCE_METRICS = {"levenshtein": levenshtein,
140+
"damerau_levenshtein": damerau_levenshtein}
141+
142+
137143
def similarity(a: str, b: str, *, metric: str = "jaro_winkler") -> float:
138144
"""Return a normalised ``[0, 1]`` similarity for ``metric``.
139145
140146
Edit-distance metrics are converted to ``1 - distance / max_len``.
141147
"""
142-
if metric in ("jaro", "jaro_winkler", "jaccard", "dice"):
143-
return globals()[metric](a, b)
144-
if metric in ("levenshtein", "damerau_levenshtein"):
148+
if metric in _SIMILARITY_METRICS:
149+
return _SIMILARITY_METRICS[metric](a, b)
150+
if metric in _DISTANCE_METRICS:
145151
longest = max(len(a), len(b))
146152
if longest == 0:
147153
return 1.0
148-
return 1 - globals()[metric](a, b) / longest
154+
return 1 - _DISTANCE_METRICS[metric](a, b) / longest
149155
raise ValueError(f"unknown metric: {metric!r}; choose from {_METRICS}")

0 commit comments

Comments
 (0)