Cheerful Curmudgeon

A complete lack of ideas and the power to express them.

  • Home
  • About Me
    • Art Zemon’s PGP Key
    • Privacy Policy
  • Bede BD-4C
    • Hall of Fame
  • Piper Arrow

Python Singleton

March 5, 2014 Art Zemon

I needed a singleton database class in a Python 2.7 program and wrote it this way.

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Database():
    __metaclass__ = Singleton
    def __init__(self):
        self.db = MySQLdb.connect(...)

I like this pattern but I realized that this is even more elegant:

class Database():
    db = MySQLdb.connect(...)

    def __init__(self):
        pass

It works because I do not really need the whole Database class to be a singleton. All I really want is a single database connection.

Software

Recent Posts

  • In Gratitude for Your Support May 2, 2026
  • STL2NOLA 22 – Tunica Resorts, MS to Memphis, TN – I Made It! May 1, 2026
  • STL2NOLA 21 – Clarksdale, MS to Tunica Resorts, MS – Return of the Headwinds April 30, 2026
  • STL2NOLA 20 – Greenville, MS to Clarksdale, MS April 29, 2026
  • STL2NOLA 19 – Roy’s Cabins, MS to Greenville, MS April 27, 2026

About Art Zemon

Omni-curious geek. Husband. Father. Photographer. Bicycle tourist. Airplane builder & pilot. Retired computer engineer.

Categories

  • Aviation (261)
    • Bede BD-4C (174)
    • Soaring (5)
  • Bicycling (60)
    • St. Louis to Atlanta (8)
    • St. Louis to New Orleans (22)
    • St. Peters to Minneapolis (18)
  • Business (48)
  • Cabbages & Kings (26)
  • Communicating (37)
  • Ecology (21)
  • Economy (8)
  • Family (35)
  • Finding the Good (44)
  • Fun (188)
    • Six Word Stories (8)
  • Gardening (5)
  • Genealogy (5)
  • Government (35)
  • Health (68)
  • Judaism (11)
  • Men (12)
  • Mideast (5)
  • Movies (8)
  • Philosophy (15)
  • Photography (29)
  • Rants & Raves (106)
  • Recommendations (35)
  • Safety (38)
  • Science (22)
    • Biology (7)
    • Physics (7)
    • Pyschology (3)
  • Technology (196)
    • eBooks (7)
    • Internet (66)
    • Software (63)
    • VOIP (5)
  • Travel (44)
  • Tzedakah (13)
  • Women (5)

You Will Also Like

  • Art Zemon's Genealogy
  • Art Zemon's Photos
  • Mastodon @babka.social
  • Mastodon @raphus.social

Search

#DonorForLife

6 gallon blood donor badge
#DonorForLife - Give Blood - Save Lives

Archives

Copyright © 2026 · Daily Dish Pro Theme on Genesis Framework · WordPress · Log in