Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Final QA #588

Merged
merged 1 commit into from
Sep 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading