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

查看:35
本文介绍了为什么* 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)时,所有位置参数都放在一个 tuple 中.python 2 3 文档,但我没有找到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,*,中间,最后=顺序)在接受"下指出

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 tuple 的事实,使得进一步的处理变得更加困难.只是在引入这种包装的早期阶段不使用包装纸吗?如果是这样,为什么在python3中没有其他兼容中断更改(PEP3132倾向于简化处理而不是一致性)(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?

推荐答案

我不知道这是否是它的背后思想,但是处理起来很容易(即使使用 tuple 数据并不难)可能会引起混乱.

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天全站免登陆