How to change the PARSER_FORMATTER when using python's argh library

Question:

Using the Argh library for Python I want to provide another PARSER_FORMATTER when I dispatch my function with argh.dispatch_command.

I tried:

import argh
import argparse

argh.PARSER_FORMATTER = argparse.RawTextHelpFormatter

def myfunct(arg, param=None):
    pass # here my working code

if __name__ == '__main__':
    argh.dispatch_command(myfunct)

But when called with --help the resulting program still sprints
default values. So it still seems to use Argh’s CustomFormatter
instead of argparse’s RawTextHelpFormatter I try to provide.

Strangely when I use set_default_command and provide the parser myself, it works:

import argh
import argparse

argh.PARSER_FORMATTER = argparse.RawTextHelpFormatter

def myfunct(arg, param=None):
    pass # here my working code

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
         formatter_class=argh.PARSER_FORMATTER)
    argh.set_default_command(parser, myfunct)
    argh.dispatch(parser)

So the problem must relate to internal visibility of PARSER_FORMATTER in Argh. How can I change argh.PARSER_FORMATTER for the Argh module itself, so that argh.dispatch_command uses it? This should be possible, or am I on the wrong track here?

Asked By: halloleo

||

Answers:

You’re seeing this behavior because Dispatching.py imports the PARSER_FORMATTER constant into its own namespace at import time and subsequently, dispatch_command and dispatch_commands functions refer to the local constant to get the formatter class.

To achieve what you want, the library would need to make an explicit choice to refer to the value in argh.constants namespace. Illustration. Until and unless that happens, the following code snippet may be helpful:

import argparse
import argh

# argh.PARSER_FORMATTER = argparse.RawTextHelpFormatter
argh.dispatching.PARSER_FORMATTER = argparse.RawTextHelpFormatter

def myfunct(arg, param=None):
    pass # here my working code

if __name__ == '__main__':
    argh.dispatch_command(myfunct)

Answered By: yogesh garg

Monkey-patching external libraries is not recommended because it makes your code fragile. argh.ArghParser is a subclass of ArgumentParser, so you can simply pass your constant to its constructor.

Answered By: Andy Mikhaylenko
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.