Why is the decorated class losing its docs?
I am currently implementing an API for which I need to decorate a class Wrapper
, but I want it to store its docstring to make it available to the API user. Take a look at the following minimal working example:
class ClassDecorator:
"""ClassDecorator docstring
"""
def __init__(self, enableCache=True):
self.enableCache = enableCache
def __call__(self, wrapper):
def numericalmathfunction(*args, **kwargs):
func = wrapper(*args, **kwargs)
return func
return numericalmathfunction
@ClassDecorator(enableCache=True)
class Wrapper(object):
"""Wrapper docstring
Instructions on how to use the Wrapper
"""
def __init__(self, p):
self.p = p
model = Wrapper(4)
print model.__doc__
print Wrapper.__doc__
This returns
Wrapper docstring
None
Instances Wrapper
do preserve the docstring, which is good, but Wrapper
doesn't by itself. If the user wants to know how to use Wrapper
with the help help(Wrapper)
, he will not get what he wants.
I know I can just copy paste the dosctring into numericalmathfunction
, but the decorator will be used on multiple classes with different docstrings.
Any ideas on how to numericalmathfunction
systematically inherit the docstrings of the wrapped class?
source to share
Use functools.wraps()
to update decorator attributes:
from functools import wraps
class ClassDecorator:
"""ClassDecorator docstring
"""
def __init__(self, enableCache=True):
self.enableCache = enableCache
def __call__(self, wrapper):
@wraps(wrapper) # <-----------
def numericalmathfunction(*args, **kwargs):
func = wrapper(*args, **kwargs)
return func
return numericalmathfunction
@ClassDecorator(enableCache=True)
class Wrapper(object):
"""Wrapper docstring
Instructions on how to use the Wrapper
"""
def __init__(self, p):
self.p = p
See the standard library documentation for functools.wrap .
source to share