Traverse f2py data structure with the following visit function: def visit(item, parents, result, *args, **kwargs): """ parents is a list of key-"f2py data structure" pairs from which items are taken from. result is a f2py data structure that is filled with the
(obj, visit, parents=[], result=None, *args, **kwargs)
| 3563 | |
| 3564 | |
| 3565 | def traverse(obj, visit, parents=[], result=None, *args, **kwargs): |
| 3566 | '''Traverse f2py data structure with the following visit function: |
| 3567 | |
| 3568 | def visit(item, parents, result, *args, **kwargs): |
| 3569 | """ |
| 3570 | |
| 3571 | parents is a list of key-"f2py data structure" pairs from which |
| 3572 | items are taken from. |
| 3573 | |
| 3574 | result is a f2py data structure that is filled with the |
| 3575 | return value of the visit function. |
| 3576 | |
| 3577 | item is 2-tuple (index, value) if parents[-1][1] is a list |
| 3578 | item is 2-tuple (key, value) if parents[-1][1] is a dict |
| 3579 | |
| 3580 | The return value of visit must be None, or of the same kind as |
| 3581 | item, that is, if parents[-1] is a list, the return value must |
| 3582 | be 2-tuple (new_index, new_value), or if parents[-1] is a |
| 3583 | dict, the return value must be 2-tuple (new_key, new_value). |
| 3584 | |
| 3585 | If new_index or new_value is None, the return value of visit |
| 3586 | is ignored, that is, it will not be added to the result. |
| 3587 | |
| 3588 | If the return value is None, the content of obj will be |
| 3589 | traversed, otherwise not. |
| 3590 | """ |
| 3591 | ''' |
| 3592 | |
| 3593 | if _is_visit_pair(obj): |
| 3594 | if obj[0] == 'parent_block': |
| 3595 | # avoid infinite recursion |
| 3596 | return obj |
| 3597 | new_result = visit(obj, parents, result, *args, **kwargs) |
| 3598 | if new_result is not None: |
| 3599 | assert _is_visit_pair(new_result) |
| 3600 | return new_result |
| 3601 | parent = obj |
| 3602 | result_key, obj = obj |
| 3603 | else: |
| 3604 | parent = (None, obj) |
| 3605 | result_key = None |
| 3606 | |
| 3607 | if isinstance(obj, list): |
| 3608 | new_result = [] |
| 3609 | for index, value in enumerate(obj): |
| 3610 | new_index, new_item = traverse((index, value), visit, |
| 3611 | parents=parents + [parent], |
| 3612 | result=result, *args, **kwargs) |
| 3613 | if new_index is not None: |
| 3614 | new_result.append(new_item) |
| 3615 | elif isinstance(obj, dict): |
| 3616 | new_result = dict() |
| 3617 | for key, value in obj.items(): |
| 3618 | new_key, new_value = traverse((key, value), visit, |
| 3619 | parents=parents + [parent], |
| 3620 | result=result, *args, **kwargs) |
| 3621 | if new_key is not None: |
| 3622 | new_result[new_key] = new_value |
no test coverage detected