bor.borygmus

A programming weblog by Hao Lian. • A long walk through an angry forest. • A series of memory leaks brought on by senility.

Let’s talk about SQLAlchemy, __init__(), and __repr__()!

It’s another post about Python. And SQLAlchemy. There’s got to be a way to monetize this.

Let’s say we have this, because we are young powerful virile men and women capable of great sexy things.

user_table = Table(
    'user', meta.metadata,
    Column('id', Integer, primary_key=True),
    Column('name', Unicode(100), unique=True),
    Column('strength', Integer))

class User(object): pass

mapper(User, user_table)

If you are lost, maps are on the table in the corner to your left. No, not the sparkly table, that’s Django’s. The solid wooden table. Yes, that one.

Now we journey out into the world, using our new User class.

>>> User(name=u'Gosh McMuffin', strength=10)
[snip]
TypeError: __init__() got an unexpected keyword argument 'name'

Ah. SQLAlchemy is not Magic School Bus ORM. You never defined an __init__() on User. Neither did our mapper() call. And this makes sense: We don’t want a function that monkeypatches an entire class. It gives into The Temptation of Globals; any monkeypatching we do is only available in that thread and we just shot down the chances of anybody reusing our code without growing a few more gray hairs. It’s rude. And, worst of all, it’s un-Pythonic. What to do, what to do.

Jump.
[(December 28, 2009) .]

WebMynd has a great little post about extending SQLAlchemy to back Amazon’s Simple Storage Service. I wasn’t even aware of MapperExtension until now. If you love reading about all the little nooks and crannies of SQLAlchemy, check this out. I also just realized that the Mike Bayer who commented on bor.borygmus’s first grumble is the same person who created SQLAlchemy, which is marvelous.

[(July 19, 2009) .]

Google App Engine’s datastore API is a continuation of a trend that the outstanding Python SQLAlchemy started, namely to re-purpose the class, an object-oriented concept, as a declaration of a table. Take, for example, the SA example

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

which by all standards seems primitive. I have to call declarative_base? And what are those underscores doing in my pristine class? Can’t you pluralize the table for me? I have to sit down, I have a headache now. SQL is hard.

Jump.

[(January 2, 2009) .]