[Tutor] using **kwargs in __init__() as attributes

Kent Johnson kent37 at tds.net
Mon Oct 1 17:58:04 CEST 2007


Dave Kuhlman wrote:
> On Mon, Oct 01, 2007 at 04:51:53PM +0200, J?nos Juh?sz wrote:
>> Dear Tutors,
>>
>> I would like to make a new class instance, where
>> the intance attributes coming from the kwargs hash.
>>
>> class ADUser:
>>     def __init__(self, **kwargs):
>>         for key in kwargs.keys():
>>             self.key = kwargs[k]
>>
> 
> You are asking a more sophisticated form of a question that has
> been asked on this list several times before: 
> 
>     "How do I create names in a namespace from string values?"
> 
> It's likely that you do not really want (or need) to do this.

Getting and setting attribute values by name is easy and well supported 
using getattr() and setattr(). IMO this is not in the same category as 
setting a variable name in the local or global namespace.

The self.__dict__.update(kwargs) method is from a recipe by none other 
than Alex Martelli:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308

> If you are determined to create names in a namespace, on the fly,
> look at the "exec" command (http://docs.python.org/ref/exec.html).
> But, that's a dangerous way to code.

In this case setattr() is all that is needed and it is safe.

Kent


More information about the Tutor mailing list