I've seen this SO question (this is not a duplicate): Python bare asterisk in function argument

我已经看到了这个问题(这不是重复的):函数参数中的Python裸星号

In python-3.x you can add a bare * to the function arguments, this means that (quote from docs):

在python-3.x中,您可以向函数参数添加一个裸*,这意味着(引自docs):

Parameters after “*” or “*identifier” are keyword-only parameters and may only be passed used keyword arguments.

“*”或“* identifier”之后的参数是仅限关键字的参数,并且只能传递使用的关键字参数。

Ok, so, I've defined a function:

好的,我已经定义了一个函数:

>>> def f(a, b, *, c=1, d=2, e=3):
...     print('Hello, world!')
... 

I can pass c, d and e variable values only by specifying keywords:

我只能通过指定关键字来传递c,d和e变量值:

>>> f(1, 2, 10, 20, 30)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 2 positional arguments but 5 were given
>>> f(1, 2, c=10, d=20, e=30)
Hello, world!

Questions are:

问题是:

  • What is the motivation for this kind of restriction/syntax sugar?
  • 这种限制/语法糖的动机是什么?
  • What use cases does it cover?
  • 它涵盖了哪些用例?
  • Is it really used in third-party libraries that switched to python3?
  • 它是否真的用于切换到python3的第三方库?

Some "real-world" examples would help a lot. Thanks in advance.

一些“现实世界”的例子会有很大帮助。提前致谢。

2 个解决方案

#1


15

PEP 3102 explains the rationale pretty clearly: the point is to allow functions to accept various "options" that are essentially orthogonal in nature. Specifying these positionally is awkward both on the defining and calling side, since they don't have any obvious "priority" that would translate into a positional order.

PEP 3102非常清楚地解释了基本原理:重点是允许函数接受本质上基本上正交的各种“选项”。在定义和调用方面,在位置上指定这些都很尴尬,因为它们没有任何明显的“优先级”可以转化为位置顺序。

There are lots of example of functions that would benefit from this in various libraries. For instance, the call signature of pandas.read_csv is:

在各种库中有很多功能可以从中受益。例如,pandas.read_csv的调用签名是:

def parser_f(filepath_or_buffer,
                 sep=sep,
                 dialect=None,
                 compression=None,

                 doublequote=True,
                 escapechar=None,
                 quotechar='"',
                 quoting=csv.QUOTE_MINIMAL,
                 skipinitialspace=False,
                 lineterminator=None,

                 header='infer',
                 index_col=None,
                 names=None,
                 prefix=None,
                 skiprows=None,
                 skipfooter=None,
                 skip_footer=0,
                 na_values=None,
                 na_fvalues=None,
                 true_values=None,
                 false_values=None,
                 delimiter=None,
                 converters=None,
                 dtype=None,
                 usecols=None,

                 engine='c',
                 delim_whitespace=False,
                 as_recarray=False,
                 na_filter=True,
                 compact_ints=False,
                 use_unsigned=False,
                 low_memory=_c_parser_defaults['low_memory'],
                 buffer_lines=None,
                 warn_bad_lines=True,
                 error_bad_lines=True,

                 keep_default_na=True,
                 thousands=None,
                 comment=None,
                 decimal=b'.',

                 parse_dates=False,
                 keep_date_col=False,
                 dayfirst=False,
                 date_parser=None,

                 memory_map=False,
                 nrows=None,
                 iterator=False,
                 chunksize=None,

                 verbose=False,
                 encoding=None,
                 squeeze=False,
                 mangle_dupe_cols=True,
                 tupleize_cols=False,
                 infer_datetime_format=False):

Except for the filepath, most of these are orthogonal options that specify different aspects of how a CSV file is to be parsed. There's no particular reason why they would be passed in any particular order. You'd go nuts keeping track of any positional order for these. It makes more sense to pass them as keywords.

除文件路径外,其中大多数是正交选项,用于指定如何解析CSV文件的不同方面。没有特别的理由说明为什么他们会以任何特定的顺序通过。你要坚持跟踪这些的任何位置顺序。将它们作为关键字传递更有意义。

Now, you can see that pandas doesn't actually define them as keyword-only arguments, presumably to maintain compatibility with Python 2. I would imagine that many libraries have refrained from using the syntax for the same reason. I don't know offhand which libraries (if any) have started using it.

现在,您可以看到pandas实际上并没有将它们定义为仅限关键字的参数,可能是为了保持与Python 2的兼容性。我想可能许多库因为同样的原因而没有使用语法。我不知道哪些库(如果有的话)已经开始使用它。

更多相关文章

  1. Python:笔记(7)——yield关键字
  2. 在Python中强制使用函数参数类型?
  3. python中函数参数传递的几种方法
  4. FieldErro:无法将关键字'date_added'解析为字段。选项包括:data_ad
  5. Python3语法——Python3函数参数的各种形式
  6. python 函数、参数及参数解构
  7. 从bash脚本传递参数到python解释器
  8. 是否可以使用argparse来捕获任意一组可选参数?
  9. Python定义函数时,不同参数类型的传递

随机推荐

  1. ABP(现代ASP.NET样板开发框架)系列之21、
  2. Javascript正则表达式对象和美元符号
  3. javascript-cropper插件翻译笔记
  4. javascript 构造函数中的属性与原型上属
  5. 使用Node.js初始化和配置AWS
  6. 深入浅出 Ajax 读书摘记2——【Ajax请求
  7. Javascript学习:案例7--对象属性和方法的
  8. css选择在IE中不起作用
  9. 注入html行模板的最佳方法
  10. require():使用module.exports vs直接分配给