1 Replies - 436 Views - Last Post: 03 July 2013 - 02:34 PM Rate Topic: -----

#1 imperialguy  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 6
  • Joined: 28-August 11

MetaClass for a class extending from sqlalchemy declarative base

Posted 02 July 2013 - 09:42 PM

I use: Python 2.6 and sqlalchemy 0.6.1

This is what I am trying to do:

from sqlalchemy.types import (
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
class SampleMeta(type):
    def __new__(cls, name, bases, attrs):
        attrs.update({   'id': Column('Id', Integer, primary_key=True),
                    'name': Column('Name', String),
                    'description': Column('Description', String),
                    'is_active': Column('IsActive', Boolean)
        return super(SampleMeta, cls).__new__(cls, name, bases, attrs)

class Sample(Base):
    __tablename__ = 'Sample'
    __table_args__ = {'useexisting': True}
    __metaclass__ = SampleMeta

    def __init__(self, id, name, description, is_active):
        self.id = id
        self.name = name
        self.description = description
        self.is_active = is_active

    def __repr__(self):
        return "<(%d, '%s', '%s', %r)>" % (self.id, self.name, self.description, self.isactive)

And the error I am getting is this:

TypeError: Error when calling the metaclass bases
    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

class Sample(object)

instead of

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

Is This A Good Question/Topic? 0
  • +

Replies To: MetaClass for a class extending from sqlalchemy declarative base

#2 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Re: MetaClass for a class extending from sqlalchemy declarative base

Posted 03 July 2013 - 02:34 PM

Well diclaimer first: I have never used sqlalchemy and metaclasses feel like dark magic to me.

Looking at the error decription I checked for the __metaclass__ atribute of Base. None there, so Python will use type(Base) insted.

this turns out to be:
>>> type(Base)
<class 'sqlalchemy.ext.declarative.DeclarativeMeta'>

So maybe in line 9
class SampleMeta(sqlalchemy.ext.declarative.DeclarativeMeta):

instead of
class SampleMeta(type):

But I am fishing in the dark here.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1