简体   繁体   English

将python元组放在函数签名中

[英]placing python tuples in function signature

In python there is this interesting, and very useful tool by which you can pattern match values from tuples on function signature.在 python 中有一个有趣且非常有用的工具,您可以通过它在函数签名上对元组中的值进行模式匹配。

def first((a, b)):
    return a

x = (4, 9)
first(x)
li = [(5, 4), (8, 9)]
map(first, li)

def second(a, b):
    # does not work the same way
    return b

I don't see any literature on use of this.我没有看到任何关于使用它的文献。 What is the vocabulary the python community uses for this? python 社区为此使用的词汇是什么? Is there a compelling reason to not use this?是否有令人信服的理由不使用它?

It's called tuple parameter unpacking and was removed in Python 3.0 .它被称为元组参数解包,并在 Python 3.0 中删除

Like @zondo said, you might not want to use it for compatibility reasons.就像@zondo 所说的那样,出于兼容性原因,您可能不想使用它。 I myself still use it occasionally in Python 2. You'll find reasons against it in the PEP of my first link, though keep in mind that those are the reasons it got removed from the language, and I think it was at least partially because it made things easier for the Python makers, which is not necessarily a reason for you or me to avoid it.我自己仍然偶尔在 Python 2 中使用它。你会在我的第一个链接的 PEP 中找到反对它的理由,但请记住,这些是它从语言中删除的原因,我认为这至少部分是因为它使 Python 制造者的工作变得更容易,这不一定是你或我避免它的原因。

In Python2, that's great.在 Python2 中,这很棒。 It is invalid syntax in Python3, however, so I would not recommend it for forward-compatability reasons.然而,它在 Python3 中是无效的语法,因此出于向前兼容的原因,我不推荐它。

The accepted answer doesn't show how to work around this, so let me just spell it out.接受的答案没有显示如何解决这个问题,所以让我把它拼出来。

The Python 2 code Python 2 代码

def fun(a, (b, c), d):
    print("a {0} b {1} c {2} d {3}".format(a, b, c, d))

can be refactored into可以重构为

def fun(a, _args, d):
    b, c = _args
    print("a {0} b {1} c {2} d {3}".format(a, b, c, d))

which is also valid Python 3 code.这也是有效的 Python 3 代码。

Call it like像这样称呼

fun(1, [2, 3], 4)

The linked PEP-3113 explains this in more detail, and provides the rationale for why this syntax was removed in Python 3.0.链接的PEP-3113更详细地解释了这一点,并提供了为什么在 Python 3.0 中删除此语法的基本原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM