Single DB connection during class's lifetime. Metaclass, singleton and __new__() examples and references.
Ryan Johnson
rj.amdphreak at gmail.com
Thu Oct 11 19:19:09 EDT 2018
I am working on using mysql.connector in a class and have found an example of how to create a single connection that spans the lifetime of all instances of the class:
https://softwareengineering.stackexchange.com/a/358061/317228
however, I do not understand a few things about the class, including
1. Why it is subclassed as an object: `class Postgres(object):` ? I thought classes were necessarily objects.
2. Why is this portion of code directly addressing the class, instead of using the `cls` reference variable?
connection = Postgres._instance.connection = psycopg2.connect(**db_config)
cursor = Postgres._instance.cursor = connection.cursor()
3. And is it me or does anyone else think {anydb}.connector’s usage is messy and inelegant? Ex:
print('connecting to PostgreSQL database...')
connection = Postgres._instance.connection = psycopg2.connect(**db_config)
cursor = Postgres._instance.cursor = connection.cursor()
cursor.execute('SELECT VERSION()')
db_version = cursor.fetchone()
Why can’t we associate the focus of the connection with the connection itself, instead of creating a separate cursor object?
Also, within the code example, and in Python in general, why does there needs to be a __new__ constructor when there’s an __init__ constructor? I’ve read about the usage of singletons. It seems you could create singletons within __init__ or __new__ . Any enlightenment would be really helpful. I am very sleep-deprived, so I’m sorry if this seems like a dumb question.
I have read the official docs. Have also been reading “Python 3: Patterns, Recipes, and Idioms”. The first was mildly helpful but I still don’t see the benefit of a __new__ constructor.
Why is there dislike for Metaclasses?
Thanks, and I’ll have better incisive questions in the future.
Sent from Mail for Windows 10
More information about the Python-list
mailing list