Skip to content

Commit

Permalink
Use get_close_matches instead of custom function
Browse files Browse the repository at this point in the history
The Python standard module difflib contains a function we can use to
replace the function stolen from Rosetta Code.  If the case where the
attribute name is incorrect, but it is reasonably close to a correct
name, that name is suggested to the user.  Otherwise, no suggestion is
made.
  • Loading branch information
sgdecker committed Oct 27, 2021
1 parent bad7f23 commit af035bb
Showing 1 changed file with 8 additions and 19 deletions.
27 changes: 8 additions & 19 deletions src/metpy/plots/declarative.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import contextlib
import copy
from datetime import datetime, timedelta
from difflib import get_close_matches
from itertools import cycle
import re

Expand Down Expand Up @@ -513,23 +514,6 @@ class ValidationMixin:

def __setattr__(self, name, value):
"""Set only permitted attributes."""
def _levenshtein(s1, s2):
"""Stolen from rosettacode.org."""
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for index2, char2 in enumerate(s2):
new_distances = [index2 + 1]
for index1, char1 in enumerate(s1):
if char1 == char2:
new_distances.append(distances[index1])
else:
new_distances.append(1 + min((distances[index1],
distances[index1 + 1],
new_distances[-1])))
distances = new_distances
return distances[-1]

allowlist = ['ax',
'data',
'handle',
Expand All @@ -541,9 +525,14 @@ def _levenshtein(s1, s2):
if name in allowlist or name.startswith('_'):
super().__setattr__(name, value)
else:
alt = sorted(allowlist, key=lambda x: _levenshtein(name, x))[0]
closest = get_close_matches(name, allowlist, n=1)
if closest:
alt = closest[0]
suggest = f" Perhaps you meant '{alt}'?"
else:
suggest = ''
obj = self.__class__
msg = f"'{name}' is not a valid attribute for {obj}. Perhaps you meant '{alt}'?"
msg = f"'{name}' is not a valid attribute for {obj}." + suggest
raise AttributeError(msg)


Expand Down

0 comments on commit af035bb

Please sign in to comment.