pythondecoratordocstringpython-cmd

Python cmd dynamic docstrings for do_help() function


I'm working on a Pythonic command-line "flashcard" app for helping users learn different languages. I would like to use Python's cmd library to speed up development--of particular interest is the cmd.Cmd class's do_help() method, which prints off the doc strings for the classes's user methods. However, due to the multilingual nature of this application, I'd like to be able to drop in language-specific docstrings.

I read this SO question about using decorators, but I know very little about decorators, and I'd like to know if they are appropriate for my specific dilemma before investing a lot of time in learning about them.

What do you guys think? What is the best way of handling this situation?

Please let me know if you'd like more information on my problem.


Solution

  • Decorators will be able to do what you want and more besides.

    Decorator primer

    As an additional bonus, decorators are very useful tools in a wide variety of situations. They're really not that scary. In Essence, they are functions that take a function as argument and return a function. A very simple example prints the result of a call out:

    >>> def my_decorator(function):
    ...  def inner_function(*args, **kwargs):
    ...    res = function(*args, **kwargs)
    ...    print("We have: "+res)
    ...    return res
    ...
    >>> @my_decorator
    ... def add(x, y):
    ...  return x+y
    ...
    >>> add(1,2)
    We have: 3
    3
    

    This is the equivalent to

    add = my_decorator(add)
    

    For your problem, the decorator simply has to override the __doc__ property of the function.

    >>> def frenchmeup(fun):
    ...    fun.__doc__ = "Bonjour, documentation!"
    ...    return fun
    ... 
    >>> @frenchmeup
    ... def foo():
    ...   """hello doc"""
    ...   return "world"
    ... 
    >>> foo.__doc__
    'Bonjour, documentation!'
    

    Passing args into decorators

    This is pretty onerous if you have to create a decorator for each function. You could easily develop a general solution by using a documentation dictionary:

    >>> ttable = {
    ...   "FR" : {
    ...     "hello doc": "Bonjour, documentation!"
    ...   }
    ... }
    >>> def document(lang=None):
    ...   def doc_decorator(function):
    ...     if lang and lang in ttable:
    ...       function.__doc__ = ttable[lang][function.__doc__]
    ...     return function
    ...   return doc_decorator
    ... 
    >>> @document(lang="FR")
    ... def foo():
    ...   """hello doc"""
    ...   return 42
    ... 
    >>> foo.__doc__
    'Bonjour, documentation!'
    

    Not how the decorator is now generated by a function. This is more complex, but gives you the ability to pass arguments into the decorator.

    As a personal note, it took a little while before this clicked for me, but I now regularly use it in my python code.

    Strategy for automatic docstring translation

    You can actually generate the documentation dictionary programatically by inspecting your module for docstrings.

    From the comments:

    The idea is that the dictionary is automatically generated from your docstrings and then passed to a translator. If you changed the canonical (English?) docstring, then the translations would have to be changed too. By comparing the old translation table to the newly generated table, you would be able reinsert the translations for which the canonical docstring hasn't changed. You'd only have to add the translation for the new docstring.

    So, for example, after changing the foo() docstring to """goodbye, doc...""" you would re-run your table generator, and you would get a new table, with the old "hello doc" key missing, and a new key-value pair ("goodbye, doc...", "") in your translation table.

    Alternative using the help_<cmd>() style for the cmd module

    If you'd rather use the help_<cmd>() style of the cmd module for the documentation, you can use the same principle of storing your translations in a dictionary and printing out the right translation based on the LANG variable in the help command.