Inheriting automatic attributes initializer considered harmful?
Andrew Durdin
adurdin at gmail.com
Wed Oct 17 09:13:28 EDT 2007
On 10/17/07, Thomas Wittek <mail at gedankenkonstrukt.de> 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)
str(u)
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])
Andrew
More information about the Python-list
mailing list