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) .]