By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,748 Members | 1,254 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,748 IT Pros & Developers. It's quick & easy.

How to define metaclass for a class that extends from sqlalchemy declarative base

P: 15
I use: Python 2.6 and sqlalchemy 0.6.1

This is what I am trying to do:

Expand|Select|Wrap|Line Numbers
  1. from sqlalchemy.types import (
  2.         Integer,
  3.         String,
  4.         Boolean
  5.     )
  6.     from sqlalchemy.ext.declarative import declarative_base
  8.     Base = declarative_base()
  10.     class SampleMeta(type):
  11.         def __new__(cls, name, bases, attrs):
  12.             attrs.update({   'id': Column('Id', Integer, primary_key=True),
  13.                         'name': Column('Name', String),
  14.                         'description': Column('Description', String),
  15.                         'is_active': Column('IsActive', Boolean)
  16.                     })
  17.             return super(SampleMeta, cls).__new__(cls, name, bases, attrs)
  19.     class Sample(Base):
  20.         __tablename__ = 'Sample'
  21.         __table_args__ = {'useexisting': True}
  22.         __metaclass__ = SampleMeta
  24.         def __init__(self, id, name, description, is_active):
  25.    = id
  26.    = name
  27.             self.description = description
  28.             self.is_active = is_active
  30.         def __repr__(self):
  31.             return "<(%d, '%s', '%s', %r)>" % (,, self.description, self.isactive)
And the error I am getting is this:

Expand|Select|Wrap|Line Numbers
  1. TypeError: Error when calling the metaclass bases
  2.     metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
Now, if I do the same thing above by using

Expand|Select|Wrap|Line Numbers
  1. class Sample(object)
instead of

Expand|Select|Wrap|Line Numbers
  1. class Sample(Base)
it works absolutely fine.

I need to update the attributes of the class dynamically. So, I will be using dynamic attribute and column names. And I need the above piece code to work in order to be able to get there.

**Please help**
Jul 3 '13 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.