I need to resolve "multiple paths" specified like so:
p1 = 'item.element.[compact|fullsize].documents.[note|invoice]'
A list like this is expected:
['item.element.compact.documents.note', 'item.element.fullsize.documents.note',
'item.element.compact.documents.invoice', 'item.element.fullsize.documents.invoice']
Code:
def resolve_paths(path):
parts = path.split('.')
depth = len(parts)
new_paths = []
for level, part in enumerate(parts):
mult_branches = re.findall(r'\[(\w+)(?:\|(\w+))*\]', part)
if mult_branches:
mult_branches = flatten_iterable(mult_branches)
for branch in mult_branches:
interm_path = '.'.join(parts[:level] + [branch] + parts[level+1:])
new_paths.extend(resolve_paths(interm_path))
return new_paths
elif level == depth - 1:
new_paths.append(path)
return new_paths
Several tests I wrote for this function pass, but I'm not entirely happy with this solution, it's somewhat convoluted. Better solutions? Simplifications?
flatten_iterable()
? – Curt F. yesterday