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"/>
</country>
</data>''')
self.assertEqual(traverse_obj(etree, ''), None,
msg='empty str key should return `None`')
self.assertEqual(traverse_obj(etree, 'country'), list(etree),
msg='str key should lead all children with that tag name')
self.assertEqual(traverse_obj(etree, ...), list(etree),
@ -2383,9 +2385,9 @@ Line 1
msg='`text()` at end of path should give the inner text')
self.assertEqual(traverse_obj(etree, '//*[@direction]/@direction'), ['E', 'W', 'N', 'W', 'E'],
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')
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')
def test_http_header_dict(self):

View File

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