Detecting Design Patterns
For now, we described Pyttern as a tool to detect small errors in student codes. But as Pyttern growed, it became expressive enough to detect larger patterns such as Design Patterns. In this exerice, you will have to match a specific design pattern called the Singleton.
Scenario
In advanced architecture, we often use the Singleton pattern to ensure a class has only one instance. In Python, this is often implemented using a Metaclass. You can find all the details about Singletons on the refactoring.guru website
Task
Write a sub-pattern singleton.myt to detect a Metaclass-based Singleton.
Requirements:
- Use the sub-pattern header: $&Singleton(?SingletonMeta, ?Singleton)
- Block 1 (The Metaclass): Matches a class ?SingletonMeta that has an _instances dictionary and overrides __call__ to check if the class is already in _instances.
- Block 2 (The Class): Matches a class ?Singleton that uses ?SingletonMeta as its metaclass.
Example:
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
def foo(self):
# ...
INGInious