解释 lambda argparse.HelpFormatter(prog, width) [英] Explain lambda argparse.HelpFormatter(prog, width)

查看:13
本文介绍了解释 lambda argparse.HelpFormatter(prog, width)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码可以正常工作以增加帮助文本的宽度,但不清楚.lambda 函数在做什么?

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

澄清一下,问题不是为什么 lambda 函数通常有用,而是参数解析器初始化代码如何使用 lambda 函数?

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)

推荐答案

这是默认 HelpFormatter 类的 __init__ 是:

This is the __init__ for the default HelpFormatter class is:

def __init__(self,
             prog,
             indent_increment=2,
             max_help_position=24,
             width=None):

ArgumentParser 类使用此函数来获取 Formatter 实例.format_help 使用此实例来创建帮助消息.

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)

其中 self.formatter_class 是您设置的参数.所以默认调用只设置 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)

调用带有 width 参数的 HelpFormatter.

calls the HelpFormatter with the addition of the width parameter.

这里是 lambda 的等效用法,具有更简单的功能:

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)

HelpFormatter 子类.

这篇关于解释 lambda argparse.HelpFormatter(prog, width)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆