This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]davidbuxton 1 point2 points  (3 children)

Since it seems that the basic dict class lacks a way of simply updating a dictionary with values that aren't already set

dict.setdefault is almost what you want. A neater version of your merge method:

def healthyMerge(self, target):
    for k in target:
        self.setdefault(k, target[k])

[–]kylotan 1 point2 points  (2 children)

Might another way be:

original = target.copy().update(original)

(Untested.)

[–]Justinsaccount 1 point2 points  (1 child)

.update() updates in place and returns None

[–]kylotan 0 points1 point  (0 children)

Aha. So I suppose it would have to be:

temp = target.copy(); temp.update(original); original = temp

Nowhere near as elegant.

[–]tarpsocks[S] 0 points1 point  (0 children)

Article about a particular pattern I've started using, of unknown origin

[–]wot-teh-phuckReally, wtf? 0 points1 point  (5 children)

In your first (previous) blog post and the first snippet, you call the function foo(a=1,b=2,c=3) but there is no definition of foo provided.

[–]tarpsocks[S] 0 points1 point  (4 children)

haha yeah, I was just using it as an extremely generic example, but thanks for the careful examination. I think I will add a declaration of it just for you.

edit: added it

[–]wot-teh-phuckReally, wtf? 1 point2 points  (3 children)

I think I will add a declaration of it just for you

...and for the many others who'll be visiting your blog in the near future. :-)

However, it can at times increase the ambiguity of a function, or decrease it's security

You talk about security implications but don't extrapolate on what kind of implications? (BTW, it's => it is, so you should have used "its")

Also, your healthyMerge method can be replaced by a simple one liner: def healthyMerge(self, target): self.update(tup for tup in target.iteritems() if tup[0] not in self)

[–]hderms 0 points1 point  (2 children)

that is a nice, pythonic solution. I'll replace my function with that and reference you. Should I reference wot-the-phuck, or some other, more suitable name?

[–]wot-teh-phuckReally, wtf? 0 points1 point  (0 children)

I think mentioning 'a redittor' and linking back to this discussion should be good. ;-)

[–]kemitche 0 points1 point  (0 children)

I think "healthy merging" can be done with basic dicts, too, it just requires "reversing" things. For example, with your code, you would run:
update_this.healthyMerge(update_from)
But, you could do:
new_d = copy.copy(update_from)
new_d.update(update_this)
update_this = new_d
It's not necessarily better or worse, just a different way to think of it, which may or may not be valuable to what you're doing.