Question: Suppose I have a class with a constructor (or other function) that takes a variable number of arguments and then sets them as class attributes conditionally.

I could set them manually, but it seems that variable parameters are common enough in python that there should be a common idiom for doing this. But I'm not sure how to do this dynamically.

I have an example using eval, but that's hardly safe. I want to know the proper way to do this -- maybe with lambda?

```
class Foo:
    def setAllManually(self, a=None, b=None, c=None):
        if a!=None: 
            self.a = a
        if b!=None:
            self.b = b
        if c!=None:
            self.c = c
    def setAllWithEval(self, **kwargs):
        for key in **kwargs:
            if kwargs[param] != None
                eval("self." + key + "=" + kwargs[param])

```

Answer: 
You could update the `__dict__` attribute (which represents the instance attributes in the form of a dictionary) with the keyword arguments:

```
class Bar(object):
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

```

then you can:

```
>>> bar = Bar(a=1, b=2)
>>> bar.a
1

```

and with something like:

```
allowed_keys = {'a', 'b', 'c'}
self.__dict__.update((k, v) for k, v in kwargs.items() if k in allowed_keys)

```

you could filter the keys beforehand (use `iteritems` instead of `items` if you’re still using Python 2.x).
Yet another variant based on the excellent answers by [mmj](https://stackoverflow.com/a/32019483/7382307) and [fqxp](https://stackoverflow.com/a/8187408/7382307). What if we want to

1. Avoid hardcoding a list of allowed attributes
2. *Directly* and explicitly set default values for each attributes in the constructor
3. Restrict kwargs to predefined attributes by either
	* silently rejecting invalid arguments *or*, alternatively,
	* raising an error.

By "directly", I mean avoiding an extraneous `default_attributes` dictionary.

```
class Bar(object):
    def __init__(self, **kwargs):

        # Predefine attributes with default values
        self.a = 0
        self.b = 0
        self.A = True
        self.B = True

        # get a list of all predefined values directly from __dict__
        allowed_keys = list(self.__dict__.keys())

        # Update __dict__ but only for keys that have been predefined 
        # (silently ignore others)
        self.__dict__.update((key, value) for key, value in kwargs.items() 
                             if key in allowed_keys)

        # To NOT silently ignore rejected keys
        rejected_keys = set(kwargs.keys()) - set(allowed_keys)
        if rejected_keys:
            raise ValueError("Invalid arguments in constructor:{}".format(rejected_keys))

```

Not a major breakthrough, but maybe useful to someone...

**EDIT:**
If our class uses `@property` decorators to encapsulate "protected" attributes with getters and setters, and if we want to be able to set these properties with our constructor, we may want to expand the `allowed_keys` list with values from `dir(self)`, as follows:

```
allowed_keys = [i for i in dir(self) if "__" not in i and any([j.endswith(i) for j in self.__dict__.keys()])]

```

The above code excludes

* any hidden variable from `dir()` (exclusion based on presence of "\_\_"), and
* any method from `dir()` whose name is not found in the end of an attribute name (protected or otherwise) from `__dict__.keys()`, thereby likely keeping only @property decorated methods.

This edit is likely only valid for Python 3 and above.