Created
June 18, 2014 04:38
-
-
Save shazow/8f22e383035e633e58fe to your computer and use it in GitHub Desktop.
Python Metaclass woes.
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
storage = {} | |
class RegistryMeta(type): | |
def __init__(cls, name, bases, attrs): | |
super(RegistryMeta, cls).__init__(name, bases, attrs) | |
id = getattr(cls, 'id', None) | |
if not id: | |
return | |
if id in storage: | |
raise KeyError("Already registered: %s" % name) | |
storage[id] = cls | |
class Base(object): | |
__metaclass__ = RegistryMeta # <-- Works without this. | |
def __init__(self): | |
self.foo = self._compute_foo() | |
def _compute_foo(self): | |
return 42 | |
class Mixin(object): | |
def _compute_foo(self): | |
return 69 | |
class C(Base, Mixin): | |
pass | |
assert C().foo == 69 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment