Skip to content

Instantly share code, notes, and snippets.

@shazow
Created June 18, 2014 04:38
Show Gist options
  • Save shazow/8f22e383035e633e58fe to your computer and use it in GitHub Desktop.
Save shazow/8f22e383035e633e58fe to your computer and use it in GitHub Desktop.
Python Metaclass woes.
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