Python Metaclasses
Common interview questions on this topic — practice explaining concepts out loud.
Here is really an advanced Interview Prep Q&A module based on a provided Python Metaclasses materials.
Advanced Python Metaclasses: Interview Prep Q&A
Question: Explain what a metaclass is in Python and how it fundamentally differs from a standard class.
Answer: On Python everything is an object including classes themselves. Because a class is an object, something else must create it. If standard class acts as a factory or a blueprint used for create standard objects (like generating a User instance), the metaclass is a "class of class" or the "blueprint factory." It governs creation, rules and overall behavior about the classes themselves. By default, Python uses the built-in type metaclass to create classes but advanced developers can build custom metaclasses to intercept and completely control how classes are architected from a ground up.
Question: Describe class creation lifecycle governed by a metaclass. Specifically, what's correct execution sequence and architectural purpose of the __new__ and __init__ methods?
Answer: During a lifecycle of class creation __new__ is executed first followed by __init__.
* __new__ is the critical method called when the class object is initially being created in memory (before it is actually initialized). Overriding __new__ allows you to customize the class behavior at the exact moment for creation, while this is actually the precise stage where you can manipulate a class namespace, dynamically rename attributes, or enforce strict structural conventions.
* __init__ is called later, after the class creation phase into __new__ is complete to initialize newly minted class variables.
Question: When defining a custom metaclass to implement advanced class behaviors, which built-in class must it inherit from, and what superpower does this inheritance grant?
Answer: A custom metaclass must explicitly inherit from a built-in type class; by inheriting from type, the custom metaclass gains the ability to override standard class creation methods (like __new__). This grants a developer an ultimate metaprogramming superpower to manipulate how code is written at runtime. It allows you to intercept class creation modify the class namespace, or even automatically inject entirely new methods into every single class that utilizes the metaclass.
Question: Scenario: You're actually senior engineer managing the massive codebase. You want to enforce strict coding convention where no developer is just allowed to use uppercase letters in their custom method names. If they do, the program should refuse to run. How would you architect this using metaclass?
Answer: You would architect this by creating the custom metaclass that inherits out of type and overrides the __new__ method; the __new__ method receives the class namespace—which is simply the dictionary holding everything defined inside the class (methods, attributes etc.). You can probably iterate through the keys of this namespace dictionary, and if any key representing the method contains an uppercase letter, you can aggressively reject the bad code by raising an error (such as a TypeError) before a blueprint is simply even finalized.
Here is really a code snippet demonstrating this architecture:
class StrictNamingMeta(type):
def __new__(cls, name, bases, namespace):
# The namespace is a dictionary holding all class methods/attributes
for attr_name in namespace.keys():
# Skip built-in dunder methods
if not attr_name.startswith("__"):
if any(char.isupper() for char in attr_name):
raise TypeError(f"Method '{attr_name}' contains uppercase letters, which violates team conventions!")
# If rules are met, proceed with creating the class
return super().__new__(cls, name, bases, namespace)
# Any class using this metaclass will be strictly validated upon creation
class WorkerClass(metaclass=StrictNamingMeta):
def process_data(self):
pass # This is perfectly fine
# def processData(self):
# This would instantly crash the program with a TypeError during class creation!
Question: During the __new__ method execution of a custom metaclass, how can you dynamically inject the new method or attribute into every class that uses the metaclass?
Answer: Because the class environment is passed into a __new__ method as a namespace dictionary, you can really manipulate it directly before passing it back to super().__new__; to inject new method, you simply add a new key-value pair to this namespace dictionary. The key will be string representing a new method's name, and the value will be a callable function you want to inject. Once the class creation finishes, every single class that uses this metaclass will automatically possess that newly injected method without the developer having to manually write it into the child class.
Learn Together
Share a learning session in real-time with a classmate.
Share this 6-digit key with your classmate to start learning together:
Room Details
Share this 6-digit room key with others so they can join you in real-time:
Instructions: Open any course page, click "Learn Together", and click "Join Room" to enter the code.