Skip to content

Instantly share code, notes, and snippets.

@brmzkw
Last active June 21, 2016 10:47
Show Gist options
  • Save brmzkw/595e5caf100a827e07fc5fbdffab57bf to your computer and use it in GitHub Desktop.
Save brmzkw/595e5caf100a827e07fc5fbdffab57bf to your computer and use it in GitHub Desktop.
Override method pydoc in subclasses
class DynPyDoc(type):
def __new__(cls, name, bases, attrs):
start_match = 'pydoc_for_'
for attr_name, attr_value in attrs.items():
if attr_name.startswith(start_match):
method_name = attr_name[len(start_match):]
# The method is not in attrs. Search it in base classes.
base_method = None
if method_name not in attrs:
for base in bases:
base_method = getattr(base, method_name, None)
break
if base_method is None:
raise AttributeError(
"'%s' not found in base classes (%s)" % (
method_name, ', '.join(base.__name__ for base in bases)
))
# Base method found, create a copy of it to set documentation.
copy_method = lambda *args, **kwargs: base_method(*args, **kwargs)
copy_method.__name__ = method_name
copy_method.__doc__ = attr_value
attrs[method_name] = copy_method
return super(DynPyDoc, cls).__new__(cls, name, bases, attrs)
class BaseView(object):
__metaclass__ = DynPyDoc
def get(self):
""" Documentation of BaseView.get(). """
pass
class ChildView1(BaseView):
pydoc_for_get = '''
Documentation of ChildView1.get().
'''
class ChildView2(BaseView):
def get(self):
""" Documentation of ChildView2.get(). """
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment