Tom Ritchford
1 min readMay 20, 2023

--

Nice, clear article!

I have known about metaclasses for many years now, and I keep expecting to use them, and I have even started to use them in projects, and every time I have switched to a class decorator.

I can't come up with a task a metaclass can solve that a decorator can't, and we're already using decorators so widely that everyone is familiar with them.

And you can compose decorators most of the time. Try doing that with metaclasses!

An advanced Python programmer should still know about metaclasses, if only because it is useful in understanding the object model but I'm starting to believe that it has no real use in the modern toolbox.

Here’s an implementation of your example as a decorator:

def with_str(cls):
def __str__(self):
attributes = ', '.join([f'{k}={v}' for k,v in self.__dict__.items()])
return f'{self.__class__.__name__}({attributes})'

cls.__str__ = __str__
return cls


@with_str
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

I have both implementation here, and you can test to see they work:

The decorator code is a little bit shorter, but more, it doesn’t require you to understand __new__ or metaclasses — it’s just another decorator, and we are all reading and writing an awful lot of decorators these days.

Thanks for writing!

--

--

No responses yet