5

I'm using the cmd module. there's a command that I'd like to document like this:

def do_this(self,arg)
    "this command accepts these values {values}".format(values="legal values")

the reasoning being I'd like to type that list of legal values only once. I found I can change the docstring later, but I think that's a hack. Is there a way to do this?

2 Answers 2

10

Changing the docstring afterwards (by assigning to do_this.__doc__) is the only way.

Or if you want it to look nicer, you can use a decorator - but it still assigns to do_this.__doc__.

def doc(docstring):
    def document(func):
        func.__doc__ = docstring
        return func

    return document

@doc("this command accepts these values: {values}".format(values=[1, 2, 3])
def do_this(self, arg):
    pass
Sign up to request clarification or add additional context in comments.

6 Comments

You should use functools.wraps for the decorator so you don't lose anything?
@gerrit negative, this is not a wrapper (renamed the inner func to to document)
clever, I'll have to check out decorators. I'm new to python, and feel like I'm drinking from a firehouse at this point.
one quick question on this. may I use that same @doc on multiple functions? or do I need a unique doc function for each do_this function?
@kdubs this is reusable, naturally. You can have it in one module and import to others as you see fit.
|
1

As you have this values in variable, you can reference to it in doc:

# mymodule.py
legal_values = {'one', 'two', 'three'}

def do_this(self,arg)
    """this command accepts these values: see `mymodule.legal_values`"""

4 Comments

tried this. didn't seem to work. those are backticks around legal_values?
@kdubs they work if you make a HTML document of the module contents using Sphinx, similar to the Python docs. In there there'd be a hyperlink. It wouldn't work specially in the online help though.
@kdubs it doesn't insert values into docstring, but it's information for user, where to find this values. When I'll type help(do_this) or will see do_this in source, i'll understand i should see help(mymodule.legal_values) for this values.
ah. ok. I think the other answer is what I want then. it shows up in the help with cmd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.