Why do SQLAlchemy classes inheriting from Base not need a constructor?

Viewed 5743

With SQLAlchemy objects inheriting from the Base class I can pass arguments to a class for variables which aren't defined in a constructor:

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    name = Column(String(50))
    fullname = Column(String(50))
    password = Column(String(12))

    def __repr__(self):
        return "<User(name='%s', fullname='%s', password='%s')>" % (
                                self.name, self.fullname, self.password)

ed_user = User(name='ed', fullname='Ed Jones', password='edspassword')

of course, if I tried passing arguments like that to another class, to set class variables in the same way I'd get an error:

In [1]: class MyClass(object):
   ...:     i = 2
   ...:     

In [2]: instance = MyClass(i=9)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-6d3ec8445b00> in <module>()
----> 1 instance = MyClass(i=9)

TypeError: object.__new__() takes no parameters

What sort of trickery is SQLalchemy doing? Why don't they just use a constructor (i.e an __init__ method)?

1 Answers
Related