Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to docstring in python for multiple languages

I want to create a new module for myself but I also want some colleagues to be able to use it. I started writing my docstrings in English but then I realized that it will make the module useless for some of them who are not good understanding this language.

My first idea was to type both English and, on the same docstring, Spanish. But this doesn't seem right, what if I want some Russian friends to use it too? What if I've got friends who have friends all over the world who don't have any common language to read docs in?

What's the easiest way to write and then read docstrings in multiple languages?

like image 962
Rubén Cabrera Avatar asked Nov 30 '14 14:11

Rubén Cabrera


Video Answer


2 Answers

To improve on the answer by Mario, you can put the docstrings in a decorator so they'll be at the start of the function.


def doc(docstring):
    def decorate(fn):
        fn.__doc__ = docstring
        return fn
    return decorate

class MyAwesomeClass:

    @doc(_(
    """My awesome documentation for an incredible method.
 
       It's really awesome, isn't it?
       """))
    def incredible_method(with_fantastic_args):
        ...

Still not ideal, but way better than having the docstring out-of-sight/out-of-mind somewhere at the bottom.

like image 174
Matthias Urlichs Avatar answered Oct 23 '22 07:10

Matthias Urlichs


I had the same issue; sort of: The cmd module uses docstrings to print help to the end user and I really needed a way to have docstrings in multiple languages. Here's how I did it:

Have a look at this awesome tutorial for using gettext module. This enables you to translate any Python app. I use it like this:

import gettext
try:
    lang = gettext.translation('myawesomeapp', localedir='locale')
    lang.install()
except FileNotFoundError:
    _ = lambda x: x

And now, whenever you want to internationalize a docstring, follow this pattern:

class MyAwesomeClass:
    def incredible_method(with_fantastic_args):
        # Some marvellous code

    incredible_method.__doc__ = _('''\
Place here a fabulous docstrig for your incredible method.
This will be translated by the gettext module at runtime.''')

Now is the time to read that tutorial I mentioned earlier: call pygettext on your code, use poedit to create translations, and have fun.

Adiós, paisanos.

like image 28
Mario Abarca Avatar answered Oct 23 '22 05:10

Mario Abarca