Using kwargs to initialize an object
By: Kerim in python | snipplet
Way to many (possible and/or optional) parameters for a class? Here is a 5 second tip for all those old style Java-type-programmers...
Use kwargs, simple setter methods and run through the keys.
#!/usr/bin/env python # -*- coding: utf-8 -*- class myClass(): def __init__(self, **kwargs): for key in kwargs: f = getattr(self, 'set_' + key) f(kwargs[key]) def set_id(self, id=None): print(id) def set_value2(self,value): print(value) c=myClass(id="myID", value2=2)
PS: Of course you might wanna wrap that with some exception handling in case some key is wrong.




on 20 July 2010 at 09:06 Dag said …
How about for key, value in kwargs.iteritems(): setattr(self, key, value) and then you can hook @property to make stuff happen when an attribute is set?
on 20 July 2010 at 18:49 Al said …
Sometimes I also add:
def __getattr__(self, key):
if self.__dict__.has_key(key):
return self.__getattr__(key)
else:
return None
Then I can just do an "if myobj.attr != None" to test if an attribute is present, it simplifies the code and makes it more readable
on 21 July 2010 at 23:18 Dag said …
@Al Why not <code>hasattr(self, 'attr')</code>? Also your code is recursive, you should call <code>object.__getattr__</code> for new-style classes and modify <code>self.__dict__</code> for old-style. Note that <code>vars(obj)</code> is the proper way to access <code>obj.__dict__</code>. The proper way to check for presence of a key is <code>in</code>: <code>if key in vars(self)</code>. Your <code>else</code> is also redundant as is the <code>return None</code>.
Just some pointers to help you write better code, don't mean to be mean!
Blog owner: <code/> is <em>not</em> a block element.