0

I'm trying to save an Inner class object into the database with the cursor of the outer class.

The thing is if I implement the class User outside with cursor as a parameter, it can receive any cursor as parameter by mistake, and I want User to be created only inside this SpecialDatabase context.

This is an example of my classes:

import MySQLdb

class SpecialDatabase():

    def __init__(self, dbinfo):
        self._dbinfo = dbinfo

    def __enter__(self):
        self._conn = MySQLdb.connect(**self._dbinfo)
        self._cursor = self._conn.cursor()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        try:
            self._cursor.close()
            self._conn.close()
        except AttributeError:
            print('Not closable.')
            return True

    # User is an object of this database
    class User():
        ...
        def change_name(self, name):
            stmt = '''UPDATE users SET name=%s WHERE id=%s'''
            data = (name, self.id)

            # I want to execute something like this, 
            # but I don't know how to reference the cursor from the outer
            outer._cursor.execute(stmt, data)
        ...

# EDIT
dbinfo = {'host':'***', 'user':'***', 'passwd':'***', 'db':'***'}
db = SpecialDatabase(dbinfo)
...
user = db.User(id)
user.change_name("Bob")
...

Is there a way to do this?

EDIT: Added initialization of both classes

Jose M Martin
  • 373
  • 1
  • 3
  • 19
  • @stovfl it's helpful but it doesn't answer exactly my question, as User doesn't inherit from SpecialDatabase conceptually and I don't want to be able to instantiate a User object unless a SpecialDatabase is instantiated before. I don't even know if this is possible... – Jose M Martin May 06 '20 at 10:00
  • @stovfl I've edited the question with the last 5 lines in the code. – Jose M Martin May 06 '20 at 10:31
  • @stovfl Yes, I know that, but that allows to pass an incorrect db as parameter – Jose M Martin May 06 '20 at 10:39
  • ***pass an incorrect db***: Why incorrect? It seems I don't get your requirements? – stovfl May 06 '20 at 10:46
  • db_with_users_table = SpecialDatabase(dbinfo1) db_without_users_table = AnotherDatabase(dbinfo2) user = db_with_users_table.User(db_without_users, id) This gives an error because it fits your solution, but it doesn't solve the oriented object problem – Jose M Martin May 06 '20 at 11:13
  • ***`user = db_with_users_table.User(db_without_users, id)`***: Simple define `class User.__init__(self, id, dB=None)`. This allows to do `user = User(id)` and `user = User(id, db)` – stovfl May 06 '20 at 13:17

0 Answers0