Metaclass in Python

Level 5349 keystrokes

This uses a metaclass to implement the Singleton pattern, ensuring only one instance of a class exists.

Python code

# Define metaclass that inherits from type
1class SingletonMeta(type):
# Class-level dict mapping each class to its single instance
2 _instances = {}
3
# __call__ runs on Database(), before __init__
4 def __call__(cls, *args, **kwargs):
# Check if instance already exists
5 if cls not in cls._instances:
# Create new instance only if not exists
6 cls._instances[cls] = super().__call__(*args, **kwargs)
# Return existing or new instance
7 return cls._instances[cls]
8
# Define class using the singleton metaclass
9class Database(metaclass=SingletonMeta):
# Initialize database connection
10 def __init__(self):
# Mark as connected
11 self.connected = True
12
# Create first instance
13db1 = Database()
# Second call returns the same object
14db2 = Database()
# Verify both variables point to same instance
15print(f"Same instance: {db1 is db2}")

Output

Same instance: True
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • _× 16
  • (× 9
  • )× 9
  • :× 6
  • *× 6
  • =× 6
  • .× 5
  • ,× 3
  • "× 2
  • [× 2

More Python examples at level 5

← Python typing practice