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 type1class SingletonMeta(type): # Class-level dict mapping each class to its single instance2 _instances = {}3 # __call__ runs on Database(), before __init__4 def __call__(cls, *args, **kwargs): # Check if instance already exists5 if cls not in cls._instances: # Create new instance only if not exists6 cls._instances[cls] = super().__call__(*args, **kwargs) # Return existing or new instance7 return cls._instances[cls]8 # Define class using the singleton metaclass9class Database(metaclass=SingletonMeta): # Initialize database connection10 def __init__(self): # Mark as connected11 self.connected = True12 # Create first instance13db1 = Database()# Second call returns the same object14db2 = Database()# Verify both variables point to same instance15print(f"Same instance: {db1 is db2}")Output
Same instance: True
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