Re: setattr + unmapped attribute

63 views
Skip to first unread message

Bobby Impollonia

unread,
Nov 13, 2012, 11:08:58 PM11/13/12
to sqlal...@googlegroups.com
The behavior here isn't SQLAlchemy-specific. If you change:

class MyClass(Base):
    __tablename__ = 'some_table'
    id = Column(Integer, primary_key=True)

to

class MyClass(object):
    pass

, you will see the same behavior.

On Tuesday, November 13, 2012 5:05:24 PM UTC-8, MikeParent wrote:
With a mapped class instance, if I try and set an unmapped attribute, Sqlalchemy simply adds this new attribute (locally) to the object, and subsequent 'get' operations return the assigned value.

Base = declarative_base()

class MyClass(Base):
__tablename__ = 'some_table'
id = Column(Integer, primary_key=True)

           ...

           obj = MyClass()
           ## This correctly raises 'AttributeError'
           print obj.unmapped_attribute

           ## This does not fail!
           obj.unmapped_attribute = 0
           ## Also does not fail anymore, prints "0"
           print obj.unmapped_attribute 
 
I'd like to have an 'AttributeError thrown whenever I try and set a bad property, similar to the getattr() behavior. Is this possible? Maybe I'm doing something wrong?

(Using SqlAlchemy 0.7.9, Python 2.7)

MikeParent

unread,
Nov 14, 2012, 8:41:22 PM11/14/12
to sqlal...@googlegroups.com
Learn something new every day! Thanks.

Christopher Galpin

unread,
Dec 13, 2012, 1:19:39 PM12/13/12
to sqlal...@googlegroups.com, mpar...@gmail.com
Found your post with Google seeking the same.

Here is the solution, you handle this with a decorator:

def validate_column_attributes(original):
    def __setattr__(self, key, value):
        if key not in self.__table__.columns:
            raise AttributeError("'%s' has no attribute '%s'" % (self.__table__.name, key))
        return original(self, key, value)
    return __setattr__

Base = declarative_base()
Base.__setattr__ = validate_column_attributes(Base.__setattr__)
Reply all
Reply to author
Forward
0 new messages