tags:

views:

115

answers:

5

Given

class ValidationRule:
    def __init__(self, **kwargs):
        # code here

Is there a way that I can define __init__ such that if I were to initialize the class with something like ValidationRule(other='email') then self.other would be "added" to class without having to explicitly name every possible kwarg?

+8  A: 

You could do something like this:

class ValidationRule:
   def __init__(self, **kwargs):
      for (k, v) in kwargs.items():
         setattr(self, k, v)
sth
Very cool! Exactly what I was looking for.
Mark
If the kwargs list is long, you might want to use *iteritems()* instead of *items()*. For your purpose that should be fine though.
Georg
+5  A: 

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)
ony
ValidationRule is just my base class, and it doesn't have any of its own attributes, so there isn't anything they can accidentally overwrite, but otherwise, this would be a good safe guard ;) I'd probably use a blacklist instead of a whitelist in this case though, so as not to restrict them too much.
Mark
+2  A: 
class ValidationRule:
   def __init__(self, **kwargs):
      self.__dict__.update(kwargs)
newacct
+4  A: 

This may not be the cleanest way, but it works:

class ValidationRule: 
    def __init__(self, **kwargs): 
        self.__dict__.update(kwargs)

I think I prefer ony's solution because it restricts available properties to keep you out of trouble when your input comes from external sources.

Gabe
+2  A: 

You can set your kwargs arguments by updating __dict__ attribute of the instance.

class ValidationRule:
   def __init__(self, **kwargs):
       self.__dict__.update(kwargs)
Ruslan Spivak