Skip to content

Commit a9ed8d5

Browse files
committed
support setitem() for dictionary assignment, e.g. name['first']='jerry'
1 parent 4a6aa61 commit a9ed8d5

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

nameparser/parser.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,12 +91,16 @@ def __ne__(self, other):
9191
return not (u(self)).lower() == (u(other)).lower()
9292

9393
def __getitem__(self, key):
94-
if isinstance(key, text_type):
95-
return getattr(self, key)
9694
if isinstance(key, slice):
9795
return [getattr(self, x) for x in self._members[key]]
9896
else:
99-
return getattr(self, self._members[key])
97+
return getattr(self, key)
98+
99+
def __setitem__(self, key, value):
100+
if key in self._members:
101+
self._set_list(key, value)
102+
else:
103+
raise KeyError("Not a valid HumanName attribute", key)
100104

101105
def next(self):
102106
return self.__next__()

tests.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,14 +140,25 @@ def test_slice(self):
140140
self.m(hn[1:], ['John', 'P.', 'Doe-Ray', 'CLU, CFP, LUTC',''], hn)
141141
self.m(hn[1:-2], ['John', 'P.', 'Doe-Ray'], hn)
142142

143-
def test_dictionary_like(self):
143+
def test_getitem(self):
144144
hn = HumanName("Dr. John A. Kenneth Doe, Jr.")
145145
self.m(hn['title'], "Dr.", hn)
146146
self.m(hn['first'], "John", hn)
147147
self.m(hn['last'], "Doe", hn)
148148
self.m(hn['middle'], "A. Kenneth", hn)
149149
self.m(hn['suffix'], "Jr.", hn)
150150

151+
def test_setitem(self):
152+
hn = HumanName("Dr. John A. Kenneth Doe, Jr.")
153+
hn['title'] = 'test'
154+
self.m(hn['title'], "test", hn)
155+
hn['last'] = ['test','test2']
156+
self.m(hn['last'], "test test2", hn)
157+
with self.assertRaises(TypeError):
158+
hn["suffix"] = [['test']]
159+
with self.assertRaises(TypeError):
160+
hn["suffix"] = {"test":"test"}
161+
151162
def test_conjunction_names(self):
152163
hn = HumanName("johnny y")
153164
self.m(hn.first, "johnny", hn)

0 commit comments

Comments
 (0)