views:

768

answers:

3

Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables?

This is what I intend to do:

c = MyClass()
c.foo = 123
c.bar = 123

# c.foo == 123 and c.bar == 123


d = {'bar': 456}
c.update(d)

# c.foo == 123 and c.bar == 456

Something akin to dictionary update() which load values from another dictionary but for plain object/class instance?

+5  A: 

Have you tried

f.__dict__.update( b )

?

S.Lott
Thanks! Kind of hard to google for this kind of info.
chakrit
http://www.python.org/doc/2.5.2/ref/types.html or http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy. The section titled "classes" is pretty explicit on precisely how this works.
S.Lott
+4  A: 

Also, maybe it would be good style to have a wrapper around the dict's update method:

def update(self, b):
    self.__dict__.update(b)

PS: Sorry for not commenting at @S.Lott 's post but I don't have the rep yet.

hyperboreean
+2  A: 

there is also another way of doing it by looping through the items in d. this doesn't have the same assuption that they will get stored in c.__dict__ which isn't always true.

d = {'bar': 456}
for key,value in d.items():
    setattr(c,key,value)

or you could write a update method as part of MyClass so that c.update(d) works like you expected it to.

def update(self,newdata):
    for key,value in newdata:
        setattr(self,key,value)

check out the help for setattr

setattr(...)
    setattr(object, name, value)
    Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
    ''x.y = v''.
Jehiah
I already know about setattr... Can you explain more on why some items would not be in __dict__ ? I actually ended up still using this kind of loop+setattr because __dict__ somehow wasn't available.
chakrit
sure, the main difference is between class attributes and instance attributes. Only the latter are in `__dict__`. so if you haveclass Test: a = 1t = Test()the object `t` has an empty `__dict__` because a is a class attributet.b = 2now it has a `__dict__` of `{'b':2}`
Jehiah