Skip to content

Commit

Permalink
Final QA (#588)
Browse files Browse the repository at this point in the history
  • Loading branch information
gahjelle authored Sep 28, 2024
1 parent 9407c12 commit 16be0cf
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
35 changes: 35 additions & 0 deletions python-313/replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,38 @@ class Person(NamedTuple):
person = Person(name="Geir Arne", place="Oslo", version="3.12")
print(copy.replace(person, version="3.13"))
print(copy.replace(today, day=1))


# %% Create a custom class that supports copy.replace()
class NamedContainer:
def __init__(self, name, **items):
print(f"Initializing {name} with {items}")
self.name = name
self.items = items

def __replace__(self, **kwargs):
""".__replace__() is called by copy.replace()"""
if "name" in kwargs:
raise ValueError("'name' can't be updated")

print(f"Replacing {kwargs} in {self.name}")
init_kwargs = {"name": self.name} | self.items | kwargs

# Create a new object with updated arguments
cls = type(self)
return cls(**init_kwargs)

def __repr__(self):
items = [f"{key}={value!r}" for key, value in self.items.items()]
return f"{type(self).__name__}(name='{self.name}', {", ".join(items)})"


capitals = NamedContainer(
"capitals", norway="oslo", sweden="Stockholm", denmark="Copenhagen"
)
print(f"{capitals = }")

capitals = copy.replace(capitals, norway="Oslo")
print(f"{capitals = }")

# copy.replace(capitals, name="Scandinavia") # Raises an error, name can't be replaced
8 changes: 6 additions & 2 deletions python-313/typing/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@


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


def get_left_leaf_value(tree_or_leaf: Tree | int) -> int:
Expand All @@ -21,7 +23,9 @@ def get_left_leaf_value(tree_or_leaf: Tree | int) -> int:
# type Tree = list[Tree | int]
#
# def is_tree(obj: object) -> TypeIs[Tree]:
# return isinstance(obj, list)
# return isinstance(obj, list) and all(
# is_tree(elem) or isinstance(elem, int) for elem in obj
# )
#
# def get_left_leaf_value(tree_or_leaf: Tree | int) -> int:
# if is_tree(tree_or_leaf):
Expand Down

0 comments on commit 16be0cf

Please sign in to comment.