Compare commits

...

2 Commits

Author SHA1 Message Date
sepro
6798214293 Cosmetic changes 2024-01-02 11:06:46 +01:00
sepro
9cc7c6c7f9 Don't return value for special keys in list 2024-01-02 09:56:54 +01:00
2 changed files with 19 additions and 12 deletions

View File

@ -2362,6 +2362,8 @@ Line 1
<neighbor name="Colombia" direction="E"/> <neighbor name="Colombia" direction="E"/>
</country> </country>
</data>''') </data>''')
self.assertEqual(traverse_obj(etree, ''), None,
msg='empty str key should return `None`')
self.assertEqual(traverse_obj(etree, 'country'), list(etree), self.assertEqual(traverse_obj(etree, 'country'), list(etree),
msg='str key should lead all children with that tag name') msg='str key should lead all children with that tag name')
self.assertEqual(traverse_obj(etree, ...), list(etree), self.assertEqual(traverse_obj(etree, ...), list(etree),
@ -2383,9 +2385,9 @@ Line 1
msg='`text()` at end of path should give the inner text') msg='`text()` at end of path should give the inner text')
self.assertEqual(traverse_obj(etree, '//*[@direction]/@direction'), ['E', 'W', 'N', 'W', 'E'], self.assertEqual(traverse_obj(etree, '//*[@direction]/@direction'), ['E', 'W', 'N', 'W', 'E'],
msg='full python xpath features should be supported') msg='full python xpath features should be supported')
self.assertEqual(traverse_obj(etree, (0, '@name', 0)), 'Liechtenstein', self.assertEqual(traverse_obj(etree, (0, '@name')), 'Liechtenstein',
msg='special transformations should act on current element') msg='special transformations should act on current element')
self.assertEqual(traverse_obj(etree, ('country', 0, ..., 'text()', 0, {int_or_none})), [1, 2008, 141100], self.assertEqual(traverse_obj(etree, ('country', 0, ..., 'text()', {int_or_none})), [1, 2008, 141100],
msg='special transformations should act on current element') msg='special transformations should act on current element')
def test_http_header_dict(self): def test_http_header_dict(self):

View File

@ -189,17 +189,22 @@ def traverse_obj(
elif xpath and not xpath.startswith('./'): elif xpath and not xpath.startswith('./'):
xpath = f'./{xpath}' xpath = f'./{xpath}'
findings = obj.iterfind(xpath) if xpath else [obj] def apply_specials(element):
if has_specials: if special == '@':
result = [ return element.attrib
element.attrib if special == '@' if special.startswith('@'):
else try_call(element.attrib.get, args=(special[1:],)) if special.startswith('@') return try_call(element.attrib.get, args=(special[1:],))
else element.text if special == 'text()' if special == 'text()':
else None return element.text
for element in findings return None
]
if not xpath:
result = apply_specials(obj)
else: else:
result = list(findings) result = obj.iterfind(xpath)
if has_specials:
result = map(apply_specials, result)
result = list(result)
return branching, result if branching else (result,) return branching, result if branching else (result,)