Temporary swap out an attribute with a new object. Usage: with swap_attr(obj, "attr", 5): ... This will set obj.attr to 5 for the duration of the with: block, restoring the old value at the end of the block. If `attr` doesn't exist on `obj`, it will
(obj, attr, new_val)
| 1477 | |
| 1478 | @contextlib.contextmanager |
| 1479 | def swap_attr(obj, attr, new_val): |
| 1480 | """Temporary swap out an attribute with a new object. |
| 1481 | |
| 1482 | Usage: |
| 1483 | with swap_attr(obj, "attr", 5): |
| 1484 | ... |
| 1485 | |
| 1486 | This will set obj.attr to 5 for the duration of the with: block, |
| 1487 | restoring the old value at the end of the block. If `attr` doesn't |
| 1488 | exist on `obj`, it will be created and then deleted at the end of the |
| 1489 | block. |
| 1490 | |
| 1491 | The old value (or None if it doesn't exist) will be assigned to the |
| 1492 | target of the "as" clause, if there is one. |
| 1493 | """ |
| 1494 | if hasattr(obj, attr): |
| 1495 | real_val = getattr(obj, attr) |
| 1496 | setattr(obj, attr, new_val) |
| 1497 | try: |
| 1498 | yield real_val |
| 1499 | finally: |
| 1500 | setattr(obj, attr, real_val) |
| 1501 | else: |
| 1502 | setattr(obj, attr, new_val) |
| 1503 | try: |
| 1504 | yield |
| 1505 | finally: |
| 1506 | if hasattr(obj, attr): |
| 1507 | delattr(obj, attr) |
| 1508 | |
| 1509 | @contextlib.contextmanager |
| 1510 | def swap_item(obj, item, new_val): |