Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly set docstring of a method

Tags:

python

nxt

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?

like image 555
Eric Pauley Avatar asked May 09 '11 00:05

Eric Pauley


People also ask

How do you specify the docstring of a function?

Declaring Docstrings: The docstrings are declared using ”'triple single quotes”' or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.

Which is the correct location to place a docstring for a function?

Module docstrings are placed at the top of the file even before any imports. Module docstrings should include the following: A brief description of the module and its purpose. A list of any classes, exception, functions, and any other objects exported by the module.

What is the purpose of __ Doc_string __?

As mentioned above, Python docstrings are strings used right after the definition of a function, method, class, or module (like in Example 1). They are used to document our code. We can access these docstrings using the __doc__ attribute.

Should every method have a docstring?

Every public function, class, method, and module should have a docstring that describes what it does. Documentation that is specific to a function or class in the module should be in the docstring of that function or class.


2 Answers

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"
like image 87
ninjagecko Avatar answered Nov 03 '22 21:11

ninjagecko


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

setattr(foo,'__doc__',"""My Doc string""")
like image 37
Senthil Kumaran Avatar answered Nov 03 '22 23:11

Senthil Kumaran