Temporary swap out an item with a new object. Usage: with swap_item(obj, "item", 5): ... This will set obj["item"] to 5 for the duration of the with: block, restoring the old value at the end of the block. If `item` doesn't exist on `obj`, it will be
(obj, item, new_val)
| 1508 | |
| 1509 | @contextlib.contextmanager |
| 1510 | def swap_item(obj, item, new_val): |
| 1511 | """Temporary swap out an item with a new object. |
| 1512 | |
| 1513 | Usage: |
| 1514 | with swap_item(obj, "item", 5): |
| 1515 | ... |
| 1516 | |
| 1517 | This will set obj["item"] to 5 for the duration of the with: block, |
| 1518 | restoring the old value at the end of the block. If `item` doesn't |
| 1519 | exist on `obj`, it will be created and then deleted at the end of the |
| 1520 | block. |
| 1521 | |
| 1522 | The old value (or None if it doesn't exist) will be assigned to the |
| 1523 | target of the "as" clause, if there is one. |
| 1524 | """ |
| 1525 | if item in obj: |
| 1526 | real_val = obj[item] |
| 1527 | obj[item] = new_val |
| 1528 | try: |
| 1529 | yield real_val |
| 1530 | finally: |
| 1531 | obj[item] = real_val |
| 1532 | else: |
| 1533 | obj[item] = new_val |
| 1534 | try: |
| 1535 | yield |
| 1536 | finally: |
| 1537 | if item in obj: |
| 1538 | del obj[item] |
| 1539 | |
| 1540 | def args_from_interpreter_flags(): |
| 1541 | """Return a list of command-line arguments reproducing the current |
no outgoing calls