Skip to content

Instantly share code, notes, and snippets.

@eagafonov
Last active September 20, 2018 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eagafonov/c3ad34619ed2fe8f81b803d0691ba3b8 to your computer and use it in GitHub Desktop.
Save eagafonov/c3ad34619ed2fe8f81b803d0691ba3b8 to your computer and use it in GitHub Desktop.
class GetAttrNotImplementedMixin:
methods_to_be_implemented = {'foo', 'bar'} # add more method names
def __getattr__(self, name):
def _method_not_implemented(*args, **kwargs):
raise NotImplementedError("Method %s is not implemented in class %s" % (name, self.__class__.__name__))
if name in self.methods_to_be_implemented:
return _method_not_implemented
raise AttributeError(self.__class__, name)
class Foo(GetAttrNotImplementedMixin):
def __init__(self):
self.the_answer = 42
# Foo.bar is not implemented
def foo(a):
print('Foo.foo()')
class Bar(GetAttrNotImplementedMixin):
# Bar.foo is not implemented
def bar(a):
print('Bar.bar()')
Foo().foo() # OK
Bar().bar() # OK
print(Foo().the_answer)
Foo().bar() # Error
# print(Bar().the_answer) # Error
python$ python method_not_imlemented_mixin.py 
Foo.foo()
Bar.bar()

42

Traceback (most recent call last):
  File "method_not_imlemented_mixin.py", line 33, in <module>
    Foo().bar() #  Error
  File "method_not_imlemented_mixin.py", line 6, in _method_not_implemented
    raise NotImplementedError("Method %s is not implemented in class %s" % (name, self.__class__.__name__))
NotImplementedError: Method bar is not implemented in class Foo


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment