Search code examples
pythonpython-2.7setattr

Python 2.7: Is it good practice to set all args/kwargs attribute with setattr?


In this answer it is shown how to automatically set as attribute the kwargs/args passed to a class __init__

For example, one could do:

class Employee(object):
    def __init__(self, *initial_data, **kwargs):
        # EDIT
        self._allowed_attrs = ['name', 'surname', 'salary', 'address', 'phone', 'mail']

        for dictionary in initial_data:
            for key in dictionary:   
                if key in self._allowed_attrs:  # EDIT
                    setattr(self, key, dictionary[key])
        for key in kwargs:
            if key in self._allowed_attrs:  # EDIT
                setattr(self, key, kwargs[key])

In my case I already know in advance the arguments I am going to pass, so I am considering this solution only to have a less repetitive and shorter code.

Is this considered good practice? Which are the pro/cons of this solutions against manually initialise each attribute? Is there any other preferable approach?

EDIT: As the first comments/answers (rightly) focus on sanitizing arguments or listing arguments, I think this can be solved quite easily in this framework.


Solution

  • Prior discussion: Python decorator to automatically define __init__ variables, Python: Is it a good idea to dynamically create variables?

    Pros:

    • Reduces code duplication

    Cons: