Python – Is modifying an object’s __dict__ to set its properties considered Pythonic

python

I have a class that inflates objects from rows found in a database (or another source, e.g. MongoDB, a CSV file, etc.). To set the object's properties, it does something like self.__dict__.update(**properties) or obj.__dict__.update(**properties).

Is this considered Pythonic? Is this a good pattern that I should continue to use, or is this considered bad form?

Best Answer

In Python 3.3, a new type was added, types.SimpleNamespace(), and in the documentation it is described thus:

The type is roughly equivalent to the following code:

class SimpleNamespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))

Note the __init__ method of the type; you cannot get a better endorsement of the technique than the Python documentation.

Related Topic