解释lambda argparse.HelpFormatter(编排,宽度) [英] Explain lambda argparse.HelpFormatter(prog, width)

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

问题描述

此代码可以正常工作以增加帮助文本的宽度,但尚不清楚. 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(编排,宽度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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