How do I copy **kwargs to self?

mpen picture mpen · Mar 29, 2010 · Viewed 8.4k times · Source

Is there a way that I can define __init__ so keywords defined in **kwargs are assigned to the class?

For example, if I were to initialize a ValidationRule class with ValidationRule(other='email'), the value for self.other should be added to the class without having to explicitly name every possible kwarg.

class ValidationRule:
    def __init__(self, **kwargs):
        # code to assign **kwargs to .self

Answer

ony picture ony · Mar 29, 2010

I think somewhere on the stackoverflow I've seen such solution. Anyway it can look like:

class ValidationRule:
    __allowed = ("other", "same", "different")
    def __init__(self, **kwargs):
        for k, v in kwargs.iteritems():
            assert( k in self.__class__.__allowed )
            setattr(self, k, v)

This class will only accept arguments with a whitelisted attribute names listed in __allowed.