Python Metaclasses
Python is an object-oriented language that makes working with classes simple and easy. A class in python is a way to describe a specific behaviour for its instances, which are python objects . These objects of that class are created using the class as the blueprint . A metaclass in python is a way to describe a specific behaviour for its instances, which are python classes. A metaclass is the blueprint of the class itself, just like a class is the blueprint for instances of that class. The default metaclass is type, and all metaclasses must derive from type .
Class-Factory
A metaclass is mostly used as a class-factory. When you create an object by calling the class, Python creates a new class by calling the metaclass. Combined with the normal __init__ and __new__ methods, metaclasses therefore allow you to do extra things when creating a class, like registering the new class with some registry or replace the class with something else entirely. There are numerous use cases for metaclasses . Here are few:- Automatic property creation
- Automatically adding new methods
- Registering classes at creation time
- Logging and profiling
- Interface checking
Metaclass's __new__() and __init__()
- __new__(): It's a method which is called before __init__(). It creates the object and return it. We can overide this method to control how the objects are created.
- __init__(): This method just initialize the created object passed as parameter.
Metaclasses can be defined in one of the two ways shown below.
class MyMeta1(type):
def __new__(cls, name, bases, dict):
pass
class MyMeta2(type):
def __init__(self, name, bases, dict):
pass
To control the creation and initialization of the class in the metaclass , you can implement the metaclass's __new__ method and/or __init__ constructor. Most real-life metaclasses will probably override just one of them. The metaclass behaves just like a class in that it has a __new__ which creates the instance of the class and an __init__ which customizes the instance. Also, you have to use __new__ if you want to return something other than a newly created class of the type in question.
When to use Metaclasses?
In practice, it's rare that someone will have to use metaclasses. Generally speaking, you will have to rely on metaclasses when you need a dynamic behaviour that cannot be described at the object level, but rather at the class level.
A Simple metaclass
We can use type directly to make a class, without any class statement. It can be called in following ways:- When called with only one argument, it returns the type.
- When called with three parameters, it creates a class. Following arguments are passed to it:
- Class name
- Tuple having base classes inherited by class
- Class Dictionary
>>> SomeClass = type('SomeClass',(),{})
>>> SomeClass
<class '__main__.SomeClass'>
The class statement isn't just syntactic sugar, it does some extra things, like setting an adequate __qualname__ and __doc__ properties or calling __prepare__ .
The __prepare__ method
This method is called before the class body is executed and it must return a dictionary-like object that's used as the local namespace for all the code from the class body. If the metaclass has a __prepare__ attribute, it is called as namespace = metaclass.__prepare__(name, bases, **kwds). If the metaclass has no __prepare__attribute, then the class namespace is initialized as an empty ordered mapping. It was added in Python 3.0 .
Creating custom Metaclass
The main purpose of a metaclass is to change the class automatically, when it's created. Normally do this for APIs, where you want to create classes matching the current context. In orderto create your custom metaclass, it have to inherit type metaclass and usually override: custom metaclass:
>>> class MyMeta(type):
... pass
And then we can use it
>>> class DoIT(metaclass=MyMeta):
... pass
>>> type(DoIT)
<class '__main__.MyMeta'>
Related Topics
- Python Interview Questions (Part 2)
- Python Interview Questions (Part 3)
- What is python used for?
- Is Python interpreted, or compiled, or both?
- Explain how python is interpreted
- How do I install pip on Windows?
- How do you protect Python source code?
- What are the disadvantages of the Python?
- How would you achieve web scraping in Python?
- How to Python Script executable on Unix
- What is the difference between .py and .pyc files?
- What is __init__.py used for in Python?
- What does __name__=='__main__' in Python mean?
- What is docstring in Python?
- What is the difference between runtime and compile time?
- How to use *args and **kwargs in Python
- Purpose of "/" and "//" operator in python?
- What is the purpose pass statement in python?
- Why isn't there a switch or case statement in Python?
- How does the ternary operator work in Python?
- What is the purpose of "self" in Python
- How do you debug a program in Python?
- What are literals in python?
- What is Python's parameter passing mechanism?
- What is the process of compilation and Loading in python?
- Global and Local Variables in Python
- Is there a tool to help find bugs or perform static analysis?
- What does the 'yield' keyword do in Python?
- Comparison Operators != is not equal to in Python
- What is the difference between 'is' and '==' in python
- What is the difference between = and == in Python?
- How are the functions help() and dir() different?
- What is the python keyword "with" used for?
- Is all the memory freed when Python exits?
- Difference between Mutable and Immutable in Python
- Explain split() methods of "re" module in Python
- Accessor and Mutator methods in Python
- How to Implement an 'enum' in Python
- Important characteristics of Python Objects
- How to determine the type of instance and inheritance in Python
- How would you implement inheritance in Python?
- How is Inheritance and Overriding methods are related?
- How can you create a copy of an object in Python?
- How to avoid having class data shared among instances in Python?
- Static class variables in Python
- Difference between @staticmethod and @classmethod in Python
- How to Get a List of Class Attributes in Python
- Does Python supports interfaces like in Java or C#?
- What is used to create Unicode string in Python?
- Difference between lists and tuples in Python?
- What are differences between List and Dictionary in Python
- Different file processing modes supported by Python
- How do you append to a file in Python?
- What are the differences between the threading and multiprocessing?
- Is there any way to kill a Thread in Python?
- What is the use of lambda in Python?
- What is map, filter and reduce in python?
- Is monkey patching considered good programming practice?
- What is "typeerror: 'module' object is not callable"
- Python: TypeError: unhashable type: 'list'
- How to convert bytes to string in Python?