Skip to content

Instantly share code, notes, and snippets.

@Midnighter
Created June 29, 2012 11:48
Show Gist options
  • Save Midnighter/3017523 to your computer and use it in GitHub Desktop.
Save Midnighter/3017523 to your computer and use it in GitHub Desktop.
A metaclass adds a new instance of a mutable class variable to each subclass of MutableBase without the need to write this attribute into the subclass' definition, i.e., users of MutableBase need not know about it.
class MetaBase(type):
"""
Metaclass for MutableBase.
This metaclass is one of two possible solutions to having a per-class
mutable class attribute. The per-class aspect is tricky because the
attribute is a mutable object. It is thus shared among MutableBase and all
its subclasses.
Shared state of the mutable class attribute is avoided with this metaclass
by creating each class with a separate mutable instance.
"""
def __new__(mcls, cls_name, cls_bases, cls_dct):
"""
Adds a unique `dict` instance to each (sub)class.
"""
cls_dct["mutable_attr"] = dict()
return super(MetaBase, mcls).__new__(mcls, cls_name, cls_bases, cls_dct)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment