How to make docstring respect PEP257 and use docopt to match i18n with gettext?

According to PEP 257 , the docstring script command line message should be a usage message:

The pre-dock script line (stand-alone program) should be used as a usage message that is printed when the script is called with invalid or missing arguments (or possibly with the -h option, for help "). Such documentation should document the script function and syntax command lines, environment variables, and files Usage messages can be quite complex (multiple screens are full) and must be sufficient for a new user to use this command correctly, as well as olnuyu brief reference to all options and arguments for the sophisticated user.

And the document line should be the first line as the module level, before anything else is available as __doc__.

Now I also use docoptas a parser of use, so I just need to write a doc line and create a command line parser on its own, which is great.

_("""...""")

What is not so cool is that I cannot find a way to mark docstring as i18nable for gettext, so I can convert it to other languages ​​if given docopt. At the moment, the only solution I got is for usage and help messages to remain in English when all applications are translated to other lines.

As PEP 20 shows :

There should be one - and only one desirable - an easy way to do this.
Although this path may not be obvious at first, if you are not Dutch.

, docstring ?

N.B.: , gettext.install() __init__.py, _() , __doc__.

+4
3

- :

-D
--docstrings
    Extract module, class, method, and function docstrings.  These do
    not need to be wrapped in _() markers, and in fact cannot be for
    Python to consider them docstrings. (See also the -X option).

. , , :

args = docopt.docopt(_(__doc__))
+1

, , :

"""\
This is the docstring
"""

import docopt
if __name__ == "__main__":
    try:
        args = docopt.docopt(_("{docstring}").format(docstring=__doc__))
    except KeyError:
        args = docopt.docopt(_("{docstring}")) # string which will be replaced by the i18ned one.

, , , python , , - , .

, docstring gettext __docopt__, , ...

+1

:

if __name__ == "__main__":
    if hasattr(vars()['__builtins__'], '_') and not 'NullTranslations' in str(_):
        args = docopt.docopt(_("USAGE MESSAGE"))
    else:
        args = docopt.docopt(__doc__)

, ... , .

, . docstring .

0

Source: https://habr.com/ru/post/1540850/


All Articles