Tag Archives: python

I know there is not very common in Python to use the singleton pattern, but I found a nice implementation of this pattern in Python 3 Patterns, Recipes and Idioms book. Starting with that example I implemented an equivalent of the well known PHP getConnection example.

You have the code below:

This is the class that implements the Singleton pattern.

Python

1

2

3

4

5

6

7

8

classSingleton:

def__init__(self,klass):

self.klass=klass

self.instance=None

def__call__(self,*args,**kwds):

ifself.instance==None:

self.instance=self.klass(*args,**kwds)

returnself.instance

Now, we create a class and we decorate it with the Singleton class. Let’s import also MySQLdb module *.

In Python, if you have a “list” with a lot of members and you need to do many membership checks, it will be better to use a “set” instead, because the checks are linear for lists and constant for sets.