Created
August 20, 2012 02:25
-
-
Save jeamland/3399471 to your computer and use it in GitHub Desktop.
Enforced abstract base classes
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 AbstractBaseMetaClass(type): | |
def __new__(meta, classname, bases, attributes): | |
if getattr(meta, '_required_methods', None) is None: | |
meta._required_methods = [] | |
for name, attribute in attributes.items(): | |
if name == '__metaclass__': | |
continue | |
if callable(attribute): | |
meta._required_methods.append(name) | |
else: | |
for required_method in meta._required_methods: | |
if required_method not in attributes: | |
raise Exception('OMG') | |
return type.__new__(meta, classname, bases, attributes) | |
class AbstractBaseClass(object): | |
__metaclass__ = AbstractBaseMetaClass | |
def required_method(self): | |
pass | |
class CorrectClass(AbstractBaseClass): | |
def required_method(self): | |
pass | |
class IncorrectClass(AbstractBaseClass): | |
def optional_method(self): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment