Explain Lambda Argparse.HelpFormatter(prog, Width)
Solution 1:
This is the __init__ for the default HelpFormatter class is:
def __init__(self,
             prog,
             indent_increment=2,
             max_help_position=24,
             width=None):
The ArgumentParser class uses this function to fetch a Formatter instance. This instance is used by format_help to create the help message.
def _get_formatter(self):
    return self.formatter_class(prog=self.prog)
where self.formatter_class is the parameter you set. So the default invocation only sets the prog parameter.
formatter = lambda prog: argparse.HelpFormatter(prog, width=100)
calls the HelpFormatter with the addition of the width parameter. 
Here's an equivalent use of lambda with a simpler function:
In [176]: def foo(x,y):
     ...:     return x,y
     ...: 
In [177]: bar = lambda y: foo('x_str',y)
In [178]: bar('y_str')
Out[178]: ('x_str', 'y_str')
There are other ways of doing the same thing, such as
def formatter(prog):
    return argparse.HelpFormatter(prog, width=100)
or a HelpFormatter subclass. 
Solution 2:
The lambda here is simply "fixing" one of the parameters of the argparse.HelpFormatter constructor. The formatter argument to argparse.ArgumentParser takes a class that accepts one argument in its constructor. We would like to pass additional named arguments to the call we are using there... namely width=100. The way to do that is to create a second constructor that takes the same positional arguments as argparse.HelpFormatter, but "fixes" width=100 in the call.
This is a common paradigm when passing functions as arguments. Another common example is when a function takes an argument that requires a function of one variable. We have a function of two variables that we'd like to pass in, with one of the variables "fixed", so we use new_func = lambda x: old_func(x, 5). Checkout functools.partial
Post a Comment for "Explain Lambda Argparse.HelpFormatter(prog, Width)"