Python – Class decorators in Python: practical use cases

decoratorpython

I am looking for practical and non-synthetic use cases of Python class decorators. So far, the only case which made sense to me is registering a class in a publisher-subscriber system, e.g. plugins or events, something like:

@register
class MyPlugin(Plugin):
    pass

or

@recieves_notifications
class Console:
    def print(self, text):
        ...

Any other sane cases I've been thinking of could have been built on top of inheritance, metaclasses or decorating methods. Could you please share any good (or bad!) examples of using class decorators?

Thank you!

Best Answer

When writing unit tests having the @unittest.skipIf and @unittest.skipUnless can be used on either individual methods or on an entire unittest.TestCase class definition. This makes for writing tests for platform specific problems so much easier.

Example from asyncio/test_selectors

# Some platforms don't define the select.kqueue object for these tests.
# On those platforms, this entire grouping of tests will be skipped.

@unittest.skipUnless(hasattr(selectors, 'KqueueSelector'),
                 "Test needs selectors.KqueueSelector)")
class KqueueSelectorTestCase(BaseSelectorTestCase, ScalableSelectorMixIn):
...