Inheriting automatic attributes initializer considered harmful?

Andrew Durdin adurdin at
Wed Oct 17 15:13:28 CEST 2007

On 10/17/07, Thomas Wittek <mail at> wrote:
> Writing such constructors for all classes is very tedious.
> So I subclass them from this base class to avoid writing these constructors:
>   class AutoInitAttributes(object):
>       def __init__(self, **kwargs):
>           for k, v in kwargs.items():
>               getattr(self, k) # assure that the attribute exits
>               setattr(self, k, v)
> Is there already a standard lib class doing (something like) this?
> Or is it even harmful to do this?

It depends on your kwargs and where they're coming from.  You could do
something like this, for example:

    def fake_str(self):
        return "not a User"

    u = User(__str__=fake_str)

Does SQLAlchemy let you get a list of column names? If so you could do:

class AutoInitAttributes(object):
    def __init__(self, **kwargs):
        valid_attrs = set(get_column_names_from_sqlalchemy())
        # Only set valid attributes, ignoring any other kwargs
        for k in set(kwargs.keys()) & valid_attrs:
               setattr(self, k, kwargs[k])


More information about the Python-list mailing list