| 40 | |
| 41 | |
| 42 | class ValidateInStrings: |
| 43 | def __init__(self, key, valid, ignorecase=False, *, |
| 44 | _deprecated_since=None): |
| 45 | """*valid* is a list of legal strings.""" |
| 46 | self.key = key |
| 47 | self.ignorecase = ignorecase |
| 48 | self._deprecated_since = _deprecated_since |
| 49 | |
| 50 | def func(s): |
| 51 | if ignorecase: |
| 52 | return s.lower() |
| 53 | else: |
| 54 | return s |
| 55 | self.valid = {func(k): k for k in valid} |
| 56 | |
| 57 | def __call__(self, s): |
| 58 | if self._deprecated_since: |
| 59 | name, = (k for k, v in globals().items() if v is self) |
| 60 | _api.warn_deprecated( |
| 61 | self._deprecated_since, name=name, obj_type="function") |
| 62 | if self.ignorecase and isinstance(s, str): |
| 63 | s = s.lower() |
| 64 | if s in self.valid: |
| 65 | return self.valid[s] |
| 66 | msg = (f"{s!r} is not a valid value for {self.key}; supported values " |
| 67 | f"are {[*self.valid.values()]}") |
| 68 | if (isinstance(s, str) |
| 69 | and (s.startswith('"') and s.endswith('"') |
| 70 | or s.startswith("'") and s.endswith("'")) |
| 71 | and s[1:-1] in self.valid): |
| 72 | msg += "; remove quotes surrounding your string" |
| 73 | raise ValueError(msg) |
| 74 | |
| 75 | def __repr__(self): |
| 76 | return (f"{self.__class__.__name__}(" |
| 77 | f"key={self.key!r}, valid={[*self.valid.values()]}, " |
| 78 | f"ignorecase={self.ignorecase})") |
| 79 | |
| 80 | def __eq__(self, other): |
| 81 | if self is other: |
| 82 | return True |
| 83 | if not isinstance(other, ValidateInStrings): |
| 84 | return NotImplemented |
| 85 | return ( |
| 86 | self.key, |
| 87 | self.ignorecase, |
| 88 | self._deprecated_since, |
| 89 | tuple(sorted(self.valid.items())) |
| 90 | ) == ( |
| 91 | other.key, |
| 92 | other.ignorecase, |
| 93 | other._deprecated_since, |
| 94 | tuple(sorted(other.valid.items())) |
| 95 | ) |
| 96 | |
| 97 | def __hash__(self): |
| 98 | return hash(( |
| 99 | self.key, |
no outgoing calls
no test coverage detected
searching dependent graphs…