1

This code works properly to increase the width of the help text, but it's unclear. What is the lambda function doing?

EDIT: To clarify, the question is not Why are lambda functions useful in general, but instead, how is the argument parser init code using the lambda function?

import argparse
import sys

formatter = lambda prog: argparse.HelpFormatter(prog, width=100)

dummy_text = """Lorem ipsum dolor sit amet, consectetur adipiscing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
    enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
    ut aliquip ex ea commodo consequat. Duis aute irure dolor in
    reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
    pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
    culpa qui officia deserunt mollit anim id est laborum."""

parser = argparse.ArgumentParser(description=dummy_text, formatter_class=formatter)

parser.add_argument("-e", dest="destE", help=dummy_text)
parser.add_argument("-w", dest="destW", help=dummy_text)
args = parser.parse_args(sys.argv)
Steve
  • 1,064
  • 7
  • 23
  • 1
    This is basically making a customized version of `argparse.HelpFormatter` that automatically supplies 100 for its second parameter. – jasonharper Jun 02 '17 at 16:42
  • Possible duplicate of [Why are Python lambdas useful?](https://stackoverflow.com/questions/890128/why-are-python-lambdas-useful) – Andras Deak Jun 02 '17 at 16:43

2 Answers2

2

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.

hpaulj
  • 175,871
  • 13
  • 170
  • 282
1

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

Him
  • 4,322
  • 2
  • 17
  • 57
  • I don't understand the down vote. This is precisely what they are doing and why they are doing it. I use this same paradigm all the time to fix parameters. – Him Jun 02 '17 at 16:50
  • Yes, the question is "how does a lambda function work?". If you answer with whatever information that can be learned by reading a tutorial or reading the duplicate target I linked above, you shouldn't be answering in the first place. Stack Overflow is not a tutorial service. Not to mention the lack of emphasis on rebinding lambdas to names this way being an anti-pattern. – Andras Deak Jun 02 '17 at 16:54
  • The question is NOT "how does a lambda function work?". Please re-read the question. Also this is not his code, so whether or not it is an anti-pattern is irrelevant. He just wants to understand the reasoning behind why the author of the code did what they did with the lambda function, and, without being an actual mind reader, I am 99% sure that this is what they were thinking. – Him Jun 05 '17 at 14:40