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.
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:
This is the equivalent to
For your problem, the decorator simply has to override the
__doc__
property of the function.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:
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:
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 moduleIf 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.