Skip to content

Commit 8367fe0

Browse files
committed
More robust user reassigment of Match attributes
1 parent afffa25 commit 8367fe0

1 file changed

Lines changed: 23 additions & 12 deletions

File tree

‎language_tool/__init__.py‎

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
import urllib.parse
2828
import urllib.request
2929
import warnings
30-
from collections import namedtuple
30+
from collections import namedtuple, OrderedDict
3131
from functools import total_ordering
3232
from weakref import WeakValueDictionary
3333

@@ -82,28 +82,34 @@ class PathError(Error):
8282
pass
8383

8484

85+
def replacement_list(string, sep="#"):
86+
if isinstance(string, list):
87+
return string
88+
return string.split(sep) if string else []
89+
90+
8591
class Match:
8692
"""Hold information about where a rule matches text.
8793
"""
88-
_SLOTS = ("fromy", "fromx", "toy", "tox", "frompos", "topos",
89-
"ruleId", "subId", "msg", "replacements",
90-
"context", "contextoffset", "errorlength")
91-
_INT_SLOTS = {"fromy", "fromx", "toy", "tox", "frompos", "topos",
92-
"contextoffset", "errorlength"}
94+
_SLOTS = OrderedDict([
95+
("fromy", int), ("fromx", int), ("toy", int), ("tox", int),
96+
("frompos", int), ("topos", int),
97+
("ruleId", str), ("subId", str), ("msg", str),
98+
("replacements", replacement_list),
99+
("context", str), ("contextoffset", int), ("errorlength", int),
100+
("url", str),
101+
])
93102
_frompos_cache, _topos_cache = None, None
94103

95104
def __init__(self, attrib, text=None):
96105
for k, v in attrib.items():
97-
setattr(self, k, int(v) if k in self._INT_SLOTS else v)
98-
if not isinstance(self.replacements, list):
99-
self.replacements = (self.replacements.split("#")
100-
if self.replacements else [])
106+
setattr(self, k, v)
101107
self._lines = text
102108

103109
def __repr__(self):
104110
def _ordered_dict_repr():
105-
attrs = (self._SLOTS +
106-
tuple(set(self.__dict__).difference(self._SLOTS)))
111+
slots = list(self._SLOTS.keys())
112+
attrs = slots + list(set(self.__dict__).difference(slots))
107113
return "{{{}}}".format(
108114
", ".join(
109115
"{!r}: {!r}".format(attr, self.__dict__[attr])
@@ -130,6 +136,11 @@ def __str__(self):
130136
)
131137
return s
132138

139+
def __setattr__(self, name, value):
140+
if name in self._SLOTS:
141+
value = self._SLOTS[name](value)
142+
super().__setattr__(name, value)
143+
133144
def __getattr__(self, name):
134145
# Fallback to calculated `frompos` and `topos` attributes
135146
# if using unpatched LanguageTool server.

0 commit comments

Comments
 (0)