1

I'm trying inherit psycopg2 like this:

import psycopg2

class myp(psycopg):
    pass

ii = myp
ii.connect(database = "myDataBase", user = "myUser", password="myPassword")

Then it throws an error:

class myp(psycopg2._psycopg):
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)

Is it possible to inherit from psycopg2 library?

EDIT: I want to use different databases, so I just have to change the class MyDatabase. something like a wrapper. example:

import psycopg2

class MyDatabase(psycopg2):
    def connect(self):
        #do some stuff
        return psycopg2.connect(database = "myDataBase", user = "myUser",   password="myPassword")

for mysqldb import MySQLdb

class MyDatabase(MySQLdb)
    def connect(self):
        #do some stuff
        return psycopg2.connect(database = "myDataBase", user = "myUser", password="myPassword")

and derived class class MyDataBaseApp(MyDatabase): def add(self, myObjectClass): db = MyDatabase() cn = None

        try:
            cn = db.connect()
            cur = cn.cursor()
            cur.execute ("INSERT ...",(myObjectClass.parameter1, myObjectClass.parameter2))
            cn.commit()
        except MyDatabase.DatabaseError, e:
            print e
            if cn:
                cn.rollback()
        finally:
            if cn:
                cn.close()

but according to the documentation I have to do it another way, suggestions?

ivocnii
  • 31
  • 2

1 Answers1

1

Disclaimer: I'm not familiar with psycopg

Update

Seems the documentation recommends to subclass psycopg2.extensions.connection. Then, connect() is a factory function that can still be used to create new connections, but you have to provide your class as a factory, again according to the docs

Full code may have to look more like (untested):

import psycopg2

class myp(psycopg2.extensions.connection):
    pass

ii = connect(connection_factory=myp,
             database = "myDataBase", user = "myUser", password="myPassword")

Update 2

With the updated approach, you're trying to build new classes with different/divergent interfaces. Often, composition is better than inheritance, see wikipedia and this question.

Community
  • 1
  • 1
cfi
  • 10,915
  • 8
  • 57
  • 103
  • Thanks for the reply. I did your suggestion but still not working – ivocnii Sep 13 '13 at 08:08
  • If we have to guess at the errors, we cannot help you. Please post the errors. What changed? What's your exact code? – cfi Sep 13 '13 at 08:12
  • the same error as above. `import psycopg2 class myp(psycopg2.psycopg1): pass ii = myp() ii.connect(database = "myDataBase", user = "myUser", password="myPassword")` – ivocnii Sep 13 '13 at 08:21
  • I will try to implement your suggestions. thank you very much! – ivocnii Sep 13 '13 at 15:39