The declarative extension (sqlalchemy.ext.declarative) provides a __init__ that takes keyword args for attributes (at least it does in 0.4).
On Tue, Jan 13, 2009 at 4:02 AM, Christoph Haas <[email protected]> wrote: > Thanks for the code. For those who might also be interested in an ORM base > class providing __init__, update and __repr__ - this is what I use now with > 0.5 (comments welcome): > > ================================================= > import sqlalchemy as sql > from sqlalchemy import orm > > class MyOrm(object): > def __init__(self, **kw): > """Create a mapped object with preset attributes""" > for key, value in kw.iteritems(): > if hasattr(self, key): > setattr(self, key, value) > elif not ignore_missing_columns: > raise AttributeError('Cannot set attribute which is not column > in mapped table: %s' % (key,)) > > def update(self, update_dict, ignore_missing_columns=True): > """Update an object's attributes from a dictionary""" > for key, value in update_dict.iteritems(): > if hasattr(self, key): > setattr(self, key, value) > elif not ignore_missing_columns: > raise AttributeError('Cannot set attribute which is not column > in mapped table: %s' % (key,)) > > def __repr__(self): > """Return a decent printable representation of a mapped object and > its attributes.""" > atts = [] > columns = orm.object_mapper(self).mapped_table.c > for column in columns: > key = column.key > if hasattr(self, key): > col = columns.get(key) > if not (getattr(col, 'server_default', None) is not None or > isinstance(getattr(col, 'default', None), > sql.PassiveDefault) or > getattr(self, key) is None): > atts.append( (key, getattr(self, key)) ) > return self.__class__.__name__ + '(' + ', '.join(x[0] + '=' + > repr(x[1]) for x in atts) + ')' > ================================================= > > Would be nice if mapped objects could automatically get such methods > assigned. Not sure if SQLAlchemy can or should provide that or if it > broke other functionality. > > Cheers > Christoph > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en -~----------~----~----~----~------~----~------~--~---
