@@ -21,3 +21,38 @@ class Person(NamedTuple):
2121person = Person (name = "Geir Arne" , place = "Oslo" , version = "3.12" )
2222print (copy .replace (person , version = "3.13" ))
2323print (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
0 commit comments