[Python-Dev] What if replacing items in a dictionary returns the new dictionary? (original) (raw)

Roy Hyunjin Han starsareblueandfaraway at gmail.com
Thu May 5 16:37:04 CEST 2011


2011/4/29 Roy Hyunjin Han <starsareblueandfaraway at gmail.com>: It would be convenient if replacing items in a dictionary returns the new dictionary, in a manner analogous to str.replace(). What do you think?

# Current behavior x = {'key1': 1} x.update(key1=3) == None x == {'key1': 3} # Original variable has changed # Possible behavior x = {'key1': 1} x.replace(key1=3) == {'key1': 3} x == {'key1': 1} # Original variable is unchanged 2011/5/5 Giuseppe Ottaviano <giuott at gmail.com>: In general nothing stops you to use a proxy object that returns itself after each method call, something like class using(object): def init(self, obj): self.wrappee = obj def unwrap(self): return self.wrappee def getattr(self, attr): def wrapper(*args, **kwargs): getattr(self.wrappee, attr)(*args, **kwargs) return self return wrapper d = dict() print using(d).update(dict(a=1)).update(dict(b=2)).unwrap() # prints {'a': 1, 'b': 2} l = list() print using(l).append(1).append(2).unwrap() # prints [1, 2]

Cool! I never thought of that. That's a great snippet.

I'll forward this to the python-ideas list. I don't think the python-dev people want this discussion to continue on their mailing list.



More information about the Python-Dev mailing list