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: 
This is what I usually do:

```
class Foo():
    def __init__(self, **kwrgs):
        allowed_args = ('a', 'b', 'c')
        default_values = {'a':None, 'b':None} 
        self.__dict__.update(default_values)
        if set(kwrgs.keys()).issubset(allowed_args):
            self.__dict__.update(kwrgs)
        else:
            unallowed_args = set(kwrgs.keys()).difference(allowed_args)
            raise Exception (f'The following unsupported argument(s) is passed to Foo:\n{unallowed_args}')

```

For most cases I find this short code enough.

**Note**

Using setattr with for loop can negatively impact the performance of your code especially if you create a lot of this class. In my test, replacing the `__update__` with `setattr(self, key, value)` in a for loop for the Foo class above, made the class take 1.4 times longer to instantiate. This will be worst if you have more arguments to set. The for loops are slow in python so this is not a surprise.
I landed on this page with a subtly different question, but here's the answer I needed:

Try `namedtuple` class ([see this answer](https://stackoverflow.com/a/34573457/93910)), or the `@dataclass` decorator ([this question](https://stackoverflow.com/questions/47955263/what-are-data-classes-and-how-are-they-different-from-common-classes)).

These are built specifically with this kind of functionality in mind, but may be less flexible than the other answers here.