r/PythonLearning • • Sep 22 '26

Subclass mysql.connector

Any idea what I am doing wrong when trying to subclass mysql.connector like this:

import mysql.connector

class Database(mysql.connector.MySQLConnection):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    def connect(self, *args, **kwargs):
        super().connect(*args, **kwargs)

db = Database(host = '...', database = '...', user = '...', passwd = '...')
db_conn = db.connect(host = '...', database = '...', user = '...', passwd = '...')
print(f"{db_conn=}")

db_conn always returns None.

3 Upvotes

12 comments sorted by

View all comments

Show parent comment

1

u/RomfordNavy Sep 22 '26

u/Gold_Record_9157 Original post edited to include your suggestion, plus a bit. However still fails.

2

u/Gold_Record_9157 Sep 22 '26

The second method, the overload of connect, shouldn't be necessary, but if you do include it, make sure you return it's value:

def connect(self, *args, **kwargs):
    return super().connect(self, *args, **kwargs)

If you don't include the return in a function, Python adds return None so every assignment would get None as a result.

Also, because of the way Python classes work, the first argument for a method called from super should be self, I think. I'm 95% sure, so I included it in my sample

Edit: syntax