什么是裸星号的函数参数的目的是什么? [英] What is the purpose of bare asterix in function arguments?

查看:194
本文介绍了什么是裸星号的函数参数的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这个问题的SO(这不是一式两份): Python的裸星号函数参数

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

在中的python-3.x中,您可以添加一个光秃秃的 * 给函数的参数,这意味着(从的docs ):

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

参数后*或*识别符是关键字唯一的参数和
  只能被传递使用关键字参数。

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

好了,所以,我定义一个函数:

Ok, so, I've defined a function:

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

我可以通过 C D 电子只能通过指定关键字变量值:

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

>>> 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!

问题是:


  • ,这是什么样的限制/语法糖的动机是什么?

  • 它覆盖哪些用例?

  • 难道真的第三方库使用的切换到python3?

一些现实世界的例子也有很大的帮助。先谢谢了。

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

推荐答案

PEP 3102 解释理pretty明确提出:关键是让函数接受在本质上是不同的正交的选项。这些指定位置上是在定义和调用方既尴尬,因为他们没有任何明显的优先级,将转化为一个位置顺序。

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.

有很多的例子,将从此在不同库中获益功能。例如, pandas.read_csv 的调用签名是:

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:

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):

除文件路径,其中大部分是指定的CSV文件是如何被解析的不同方面正交选项。还有为什么他们会在任何特定的顺序传递没有特别的理由。你会去其中的任何位置顺序坚果保持跟踪。它更有意义,通过他们作为关键字。

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.

现在,你可以看到,大熊猫实际上并不将其定义为仅关键字参数,presumably保持与Python 2.兼容性我会想象许多图书馆已经从使用的语法出于同样的原因忍住了。我不知道随便哪个库(如果有的话)使用它已经开始。

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.

这篇关于什么是裸星号的函数参数的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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