Created
June 29, 2012 11:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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