Metaprogramming Assessment
Test your mastery of Python metaprogramming: metaclasses, descriptors, dynamic class creation, and more. These exercises demand a deep understanding of how Python constructs and manipulates classes at runtime.
Write a metaclass called SingletonMeta that ensures any class using it as its metaclass can only ever have one instance.
Database that uses SingletonMeta as its metaclass. Its __init__ should accept a name parameter and store it as self.name.Create a descriptor class called TypedField that validates the type of a value on assignment.
expected_type.__set__, raise a TypeError with the message "Expected <type_name>" if the value is not an instance of the expected type.__set_name__ to store the attribute name.Then define a class Person with:
name = TypedField(str)age = TypedField(int)The code below tries to create an immutable Point by subclassing tuple. However it raises a TypeError at runtime. Fix the bug so that Point(3, 4) works correctly and p.x / p.y return the expected values.
Do not change the property definitions or remove the tuple base class.
Read the code carefully and predict exactly what it prints. Pay close attention to when __getattr__ is called versus when it is not.
Write a function make_dataclass(class_name, **fields) that uses type() to dynamically create a class.
__init__ that accepts those fields as keyword arguments (with the given defaults).__repr__ that returns ClassName(field1=val1, field2=val2).Example: Dog = make_dataclass("Dog", name="Rex", age=3)
The auto_repr class decorator is supposed to add a __repr__ method that shows all __init__ parameters. However, it has a bug: it always prints the class name as "cls" instead of the real class name.
Fix the decorator so the repr uses the actual class name.
Read the code carefully and predict exactly what it prints. Focus on the order in which the metaclass methods execute.
The Sensor class below works but uses a regular instance dict. Refactor it to use __slots__ for memory efficiency.
Requirements:
__slots__ with the correct attribute names.__dict__.The Logged class overrides __setattr__ to record attribute changes in a log list. However, it causes infinite recursion. Fix the bug while keeping the logging behavior.
The log should collect strings in the format "set <name> = <value>". The log attribute itself should not be logged.
The code below uses a base class Shape with methods that raise NotImplementedError. Refactor it to use Python's abc module so that:
Shape is an abstract base class.area() and perimeter() are abstract methods.Shape directly raises TypeError.Circle subclass should remain functional.