Fencepost
Fencepost

Reputation: 41

SQLAlchemy Mass-Column Creation

So I have an interesting use case for declarative SQLAlchemy: I need to define about ten different sqlalchemy classes that have several hundred columns each. However, these objects will be essentially storing an array of "channels" of data so the columns will be named:

channel_51, channel_52 ... channel_272, channel_273

I could maintain a huge file with the classes declared but each class will always be of that form of channel_n through channel_m. Is there any way to turn that into a few lines of code per class instead of 300 individual lines? The challenge is that they need to be defined at the top level in order to be visible to the metadata.create_all() function and can't just be added to the class during init. I'd like something equivalent to:

for i in range(n,m):
    setattr(self, 'channel_%d' %i, Column(sqlalchemy.types.Float))

except it needs to work at the top-level of the class

Upvotes: 0

Views: 75

Answers (1)

zzzeek
zzzeek

Reputation: 75227

The most direct is to use a Table, since it is already a function call interface:

class MyClass(Base):
    __table__ = Table('mytable', Base.metadata, 
                      Column('x', Integer, primary_key=True),
                      *[Column("channel_%d" % i, Float) for i in range(51, 273)]
                )

but if you want to create Python classes using a function call interface, use type():

cols = dict(("channel_%d" % i, Column(Float)) for in range(51, 273))
cls_dict = {"__tablename__": "mytable", "id": Column('x', Integer, primary_key=True)}
cls_dict.update(cols)
MyClass = type("MyClass", (Base, ), cls_dict)

Upvotes: 1

Related Questions