为什么 *args 参数解包会给出一个元组? [英] Why does *args argument unpacking give a tuple?

查看:22
本文介绍了为什么 *args 参数解包会给出一个元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,可以像这样定义一个带有任意数量位置参数的函数:

In python, it is possible to define a function taking an arbitrary number of positional arguments like so:

def f(*args):
    print(args)
f(1, 2, 3)  # (1, 2, 3)

当被调用为 f(a, b, c) 时,所有位置参数都被放在一个 元组中.此行为在 python 23 文档,但我还没有找到 PEP

When called as f(a, b, c), all positional arguments are put together into a tuple. This behavior is described in python 2 and 3 documentation, but I haven't found a PEP to it.

PEP 3132,引入扩展的可迭代解包(first, *middle, last = sequence) 在接受"下声明

PEP 3132, introducing extended iterable unpacking (first, *middle, last = seqence) states under "Acceptance" that

使加星标的目标成为元组而不是列表.这将与函数的 *args 一致,但会使结果的进一步处理更加困难.

Make the starred target a tuple instead of a list. This would be consistent with a function's *args, but make further processing of the result harder.

进行了讨论.如果我写一个包装器,我可能还想进一步处理这样的参数:

was discussed. If I write a wrapper, I may also want to further process arguments like so:

def force_type(position, type):
    def wrapper(f):
        def new(*args, **kwargs):
            args = list(args)  # Why?
            args[position] = type(args[position])
            return f(*args, **kwargs)
        return new
    return wrapper

@force_type(1, int)
def func(a, b, c):
    assert isinstance(b, int)

由于args 是一个元组,这个进一步的处理变得更加困难.在引入的早期阶段是否没有使用包装器?如果是这样,为什么在 python3 中没有通过其他破坏兼容性的更改来改变这一点(PEP3132 倾向于处理的简便性而不是一致性(这似乎至少类似于兼容性破坏性更改中的兼容性).

This further processing is made harder by the fact args is a tuple. Were wrappers just not used at the early stages this was introduced? If so, why wasn't this changed in python3 with other compatibility breaking changes (PEP3132 favours ease of processing over consistency (which seems at least similar to compatibility in a compatibility- breaking change).

为什么函数 *args(仍然)是 tuple,即使 list 允许更容易的进一步处理?

Why are a functions *args (still) a tuple even though a list allows easier further processing?

推荐答案

我不知道这是否是它背后的想法,但是处理起来很容易(即使实例化一个 listtuple 数据并不难)可能会出现令人困惑的行为.

I don't know if this was the thinking behind it, but that ease of processing (even though instantiate a list with the tuple data is not that hard) would come at possible confusing behavior.

def fce1(*args):
   fce2(args)
   # some more code using args

def fce2(args):
   args.insert(0, 'other_val')

fce1(1, 2, 3)

编写 fce1 代码的人可能会感到惊讶,因为他们没有意识到他们稍后处理的 args 不是调用函数的内容.

Could surprise people writing fce1 code not realizing that args they deal with later on are not what the function was called with.

我还认为不可变类型在内部更容易处理并且开销更少.

I would also presume immutable types are easier to deal with internally and come with less overhead.

这篇关于为什么 *args 参数解包会给出一个元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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