MCPcopy Index your code
hub / github.com/RustPython/RustPython / swap_attr

Function swap_attr

Lib/test/support/__init__.py:1479–1507  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

1477
1478@contextlib.contextmanager
1479def 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
1510def swap_item(obj, item, new_val):

Callers 12

setUpMethod · 0.90
test_modify_builtinsMethod · 0.90
setUpMethod · 0.90
testRecursiveReprMethod · 0.90
test_recursive_reprMethod · 0.90
test_issue31492Method · 0.90
test_override_builtinMethod · 0.90
force_colorFunction · 0.85

Calls 4

hasattrFunction · 0.85
getattrFunction · 0.85
setattrFunction · 0.85
delattrFunction · 0.85

Tested by 11

setUpMethod · 0.72
test_modify_builtinsMethod · 0.72
setUpMethod · 0.72
testRecursiveReprMethod · 0.72
test_recursive_reprMethod · 0.72
test_issue31492Method · 0.72
test_override_builtinMethod · 0.72