Skip to content

Commit 16be0cf

Browse files
authored
Final QA (#588)
1 parent 9407c12 commit 16be0cf

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

python-313/replace.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,38 @@ class Person(NamedTuple):
2121
person = Person(name="Geir Arne", place="Oslo", version="3.12")
2222
print(copy.replace(person, version="3.13"))
2323
print(copy.replace(today, day=1))
24+
25+
26+
# %% Create a custom class that supports copy.replace()
27+
class NamedContainer:
28+
def __init__(self, name, **items):
29+
print(f"Initializing {name} with {items}")
30+
self.name = name
31+
self.items = items
32+
33+
def __replace__(self, **kwargs):
34+
""".__replace__() is called by copy.replace()"""
35+
if "name" in kwargs:
36+
raise ValueError("'name' can't be updated")
37+
38+
print(f"Replacing {kwargs} in {self.name}")
39+
init_kwargs = {"name": self.name} | self.items | kwargs
40+
41+
# Create a new object with updated arguments
42+
cls = type(self)
43+
return cls(**init_kwargs)
44+
45+
def __repr__(self):
46+
items = [f"{key}={value!r}" for key, value in self.items.items()]
47+
return f"{type(self).__name__}(name='{self.name}', {", ".join(items)})"
48+
49+
50+
capitals = NamedContainer(
51+
"capitals", norway="oslo", sweden="Stockholm", denmark="Copenhagen"
52+
)
53+
print(f"{capitals = }")
54+
55+
capitals = copy.replace(capitals, norway="Oslo")
56+
print(f"{capitals = }")
57+
58+
# copy.replace(capitals, name="Scandinavia") # Raises an error, name can't be replaced

python-313/typing/tree.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55

66
def is_tree(obj: object) -> TypeGuard[Tree]:
7-
return isinstance(obj, list)
7+
return isinstance(obj, list) and all(
8+
is_tree(elem) or isinstance(elem, int) for elem in obj
9+
)
810

911

1012
def get_left_leaf_value(tree_or_leaf: Tree | int) -> int:
@@ -21,7 +23,9 @@ def get_left_leaf_value(tree_or_leaf: Tree | int) -> int:
2123
# type Tree = list[Tree | int]
2224
#
2325
# def is_tree(obj: object) -> TypeIs[Tree]:
24-
# return isinstance(obj, list)
26+
# return isinstance(obj, list) and all(
27+
# is_tree(elem) or isinstance(elem, int) for elem in obj
28+
# )
2529
#
2630
# def get_left_leaf_value(tree_or_leaf: Tree | int) -> int:
2731
# if is_tree(tree_or_leaf):

0 commit comments

Comments
 (0)