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)
| 1550 | |
| 1551 | @contextlib.contextmanager |
| 1552 | def swap_attr(obj, attr, new_val): |
| 1553 | """Temporary swap out an attribute with a new object. |
| 1554 | |
| 1555 | Usage: |
| 1556 | with swap_attr(obj, "attr", 5): |
| 1557 | ... |
| 1558 | |
| 1559 | This will set obj.attr to 5 for the duration of the with: block, |
| 1560 | restoring the old value at the end of the block. If `attr` doesn't |
| 1561 | exist on `obj`, it will be created and then deleted at the end of the |
| 1562 | block. |
| 1563 | |
| 1564 | The old value (or None if it doesn't exist) will be assigned to the |
| 1565 | target of the "as" clause, if there is one. |
| 1566 | """ |
| 1567 | if hasattr(obj, attr): |
| 1568 | real_val = getattr(obj, attr) |
| 1569 | setattr(obj, attr, new_val) |
| 1570 | try: |
| 1571 | yield real_val |
| 1572 | finally: |
| 1573 | setattr(obj, attr, real_val) |
| 1574 | else: |
| 1575 | setattr(obj, attr, new_val) |
| 1576 | try: |
| 1577 | yield |
| 1578 | finally: |
| 1579 | if hasattr(obj, attr): |
| 1580 | delattr(obj, attr) |
| 1581 | |
| 1582 | @contextlib.contextmanager |
| 1583 | def swap_item(obj, item, new_val): |
no outgoing calls
searching dependent graphs…