1

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.

Community
  • 1
  • 1
weberc2
  • 7,423
  • 4
  • 41
  • 57

1 Answers1

2

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.

brice
  • 24,329
  • 7
  • 79
  • 95
  • Okay, how does that relate to [link](http://www.doughellmann.com/PyMOTW/cmd/#live-help) this? It seems this is a bit easier; however, your solution seems like it would be generally better as it would allow me to modify the docstring for developer documentation purposes as well as for user help purposes. What are your thoughts? It seems your answer is better, but are there any other details I'm failing to consider? – weberc2 Apr 02 '12 at 10:09
  • It depends on whether you want the help text to come from the docstrings or not. If you do, then the code above will save you some time, and if you declare LANG as a global, it con be configured at initialisation of your program. If you prefer to use the `help_()` style, then you can use the same principle of having a dictionary to store the i18n and do a lookup on the canonical English help string. The latter way won't need decorators. – brice Apr 02 '12 at 10:25
  • I would prefer to have a list (in the generic, non-Pythonic sense) of constants which are assigned to a separate string for each language. In your proposed solution, you have me querying a dictionary based on the function's .__doc__; however, if I change the English docstring, I'd also have to change its corresponding key in the dictionary. Would it be possible to use the fn.__doc__ variable as the dictionary key? If so, could you update this in your answer? Otherwise, I like the decorator method right now because it seems to reduce the number of methods in my class. – weberc2 Apr 02 '12 at 10:37
  • 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. – brice Apr 02 '12 at 10:42