Single DB connection during class's lifetime. Metaclass, singleton and __new__() examples and references.

Thomas Jollans tjol at tjol.eu
Fri Oct 12 02:33:50 EDT 2018


On 12/10/2018 01:19, Ryan Johnson wrote:
> 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.

This was sometimes necessary in Python 2.

> 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()

In a subclass, the `cls' argument would refer to the subclass, while 
`Postgres' would still refer to the original class. I have no idea what 
this is trying to achieve, and I think it's probably a bug. Maybe 
someone else has an idea.

> 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?

You can have multiple cursors on the same connection.

> 
> 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.

You can't create a singleton with __init__: by the time __init__ is 
called, a new instance has already been created, and you can't switch 
the object for a different one. By using __new__, you can bypass the 
creation of a new instance.

If what you want is some shared state between all instances, a class 
variable or global will do just fine and there's no need for a singleton 
instance of anything.

> Why is there dislike for Metaclasses?

They can be confusing.




More information about the Python-list mailing list