Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good real-world uses of metaclasses (e.g. in Python)

I'm learning about metaclasses in Python. I think it is a very powerful technique, and I'm looking for good uses for them. I'd like some feedback of good useful real-world examples of using metaclasses. I'm not looking for example code on how to write a metaclass (there are plenty examples of useless metaclasses out there), but real examples where you have applied the technique and it was really the appropriate solution. The rule is: no theoretical possibilities, but metaclasses at work in a real application.

I'll start with the one example I know:

  • Django models, for declarative programming, where the base class Model uses a metaclass to fill the model objects of useful ORM functionality from the attribute definitions.

Looking forward to your contributions.

like image 217
Carles Barrobés Avatar asked May 25 '10 18:05

Carles Barrobés


People also ask

What are Python metaclasses used for?

A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass.

Why do we need metaclasses?

Well, since a metaclass creates a class in certain steps, it might be useful if we could go in and manipulate that process and thereby make our own custom metaclass that would instantiate classes differently than type does.

What is the concept of a metaclass?

In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances. Not all object-oriented programming languages support metaclasses.

What is meta programming in Python?

The term metaprogramming refers to the potential for a program to have knowledge of or manipulate itself. Python supports a form of metaprogramming for classes called metaclasses. Metaclasses are an esoteric OOP concept, lurking behind virtually all Python code. You are using them whether you are aware of it or not.


1 Answers

In Python 2.6 and 3.1, the Python standard library provides an abc.ABCMeta, a meta-class for Abstract Base Classes ("ABCs"). Classes that use the meta-class can use @abstractmethod and @abstractproperty to define abstract methods and properties. The meta-class will ensure that derived classes override the abstract methods and properties.

Also, classes that implement the ABC without actually inheriting from it can register as implementing the interface, so that issubclass and isinstance will work.

For example, the collections module defines the Sequence ABC. It also calls Sequence.register(tuple) to register the built-in tuple type as a Sequence, even though tuple does not actually inherit from Sequence.

like image 138
Daniel Stutzbach Avatar answered Oct 30 '22 07:10

Daniel Stutzbach