|
| 1 | +import sys |
| 2 | + |
| 3 | +import infinicore |
| 4 | + |
| 5 | + |
| 6 | +def use_ntops(): |
| 7 | + import ntops |
| 8 | + |
| 9 | + return _TemporaryAttributes( |
| 10 | + (("ntops.torch.torch", infinicore),) |
| 11 | + + tuple( |
| 12 | + (f"infinicore.{op_name}", getattr(ntops.torch, op_name)) |
| 13 | + for op_name in ntops.torch.__all__ |
| 14 | + ) |
| 15 | + ) |
| 16 | + |
| 17 | + |
| 18 | +class _TemporaryAttributes: |
| 19 | + def __init__(self, attribute_mappings): |
| 20 | + self._attribute_mappings = attribute_mappings |
| 21 | + |
| 22 | + self._original_values = {} |
| 23 | + |
| 24 | + def __enter__(self): |
| 25 | + for attr_path, new_value in self._attribute_mappings: |
| 26 | + parent, attr_name = self._resolve_path(attr_path) |
| 27 | + |
| 28 | + try: |
| 29 | + self._original_values[attr_path] = getattr(parent, attr_name) |
| 30 | + except AttributeError: |
| 31 | + pass |
| 32 | + |
| 33 | + setattr(parent, attr_name, new_value) |
| 34 | + |
| 35 | + return self |
| 36 | + |
| 37 | + def __exit__(self, exc_type, exc_value, traceback): |
| 38 | + for attr_path, _ in self._attribute_mappings: |
| 39 | + parent, attr_name = self._resolve_path(attr_path) |
| 40 | + |
| 41 | + if attr_path in self._original_values: |
| 42 | + setattr(parent, attr_name, self._original_values[attr_path]) |
| 43 | + else: |
| 44 | + delattr(parent, attr_name) |
| 45 | + |
| 46 | + @staticmethod |
| 47 | + def _resolve_path(path): |
| 48 | + *parent_parts, attr_name = path.split(".") |
| 49 | + |
| 50 | + curr = sys.modules[parent_parts[0]] |
| 51 | + |
| 52 | + for part in parent_parts[1:]: |
| 53 | + curr = getattr(curr, part) |
| 54 | + |
| 55 | + return curr, attr_name |
0 commit comments