Explicitly set docstring of a method
Asked Answered
W

2

8

I help to maintain a package for python called nxt-python. It uses metaclasses to define the methods of a control object. Here's the method that defines the available functions:

class _Meta(type):
    'Metaclass which adds one method for each telegram opcode'

    def __init__(cls, name, bases, dict):
        super(_Meta, cls).__init__(name, bases, dict)
        for opcode in OPCODES:
            poll_func, parse_func = OPCODES[opcode]
            m = _make_poller(opcode, poll_func, parse_func)
            setattr(cls, poll_func.__name__, m)

I want to be able to add a different docstring to each of these methods that it adds. m is a method returned by _make_poller(). Any ideas? Is there some way to work around the python restriction on changing docstrings?

Werby answered 9/5, 2011 at 0:39 Comment(1)
You can also pass it into your _Meta constructor in the dict argument as _Meta(cls,name,bases,dict={'__doc__':"""docstring"""}) or call dict.update({'__doc__':"""docstring"""}) before your super call. Now you have at least 4 options.Wakashan
H
19

For plain functions:

def f():  # for demonstration
    pass

f.__doc__ = "Docstring!"
help(f)

This works in both python2 and python3, on functions with and without docstrings defined. You can also do +=. Note that it is __doc__ and not __docs__.

For methods, you need to use the __func__ attribute of the method:

class MyClass(object):

    def myMethod(self):
        pass

MyClass.myMethod.__func__.__doc__ = "A really cool method"
Haroldharolda answered 9/5, 2011 at 0:40 Comment(1)
I tried this on a class method and get an error. It turns out that on a class method, which I think is what the original question wants, you would want to do: self.method.__func__.__doc__Taxexempt
B
3

You may also use setattr on the class/function object and set the docstring.

setattr(foo,'__doc__',"""My Doc string""")
Baseboard answered 9/5, 2011 at 2:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.