from dict to member vars...?

exarkun at divmod.com exarkun at divmod.com
Thu Oct 14 14:27:10 EDT 2004


On Thu, 14 Oct 2004 14:19:43 -0400, Jeremy Jones <zanesdad at bellsouth.net> wrote:
>Diez B. Roggisch wrote:
> 
> >Christopher J. Bottaro wrote:
> >
> >  
> >
> >>Hello,
> >>
> >>Lets say I have a class instance with the following member vars:  var1, x,
> >>size.  Now lets say I have dict with the following keys:  var1, x, size.
> >>Is there an easy way to *automatically* assign all the values in the dict
> >>to corresponding (member) vars of the same name as the dict keys?
> >>    
> >>
> >
> >d = dict(...)
> >
> >for key, val in d.items():
> >   setattr(o, key, val)
> >
> >  
> >
> Why not just use update()?

  Because it is semantically different from setattr().  If any of the attributes are properties or are handled specially by __setattr__, using inst.__dict__.update() will do something very different from calling setattr() repeatedly.

  Perhaps this is not of concern to the original poster, but it could be...  Also, even if it is not relevant today, next week the code might change, and someone could be left scratching their head over why the thing isn't working right.

  Jp



More information about the Python-list mailing list