python函数可以有几个参数,什么是一个Python函数的参数最大数量?

这篇文章探讨了Python函数中关于*args和**kwargs的最大参数数量限制,并指出这个限制仅限于函数调用时,并非参数展开。实验证明,当使用*args接收大量参数时,超过256个会导致语法错误,而**kwargs不受此限制。
摘要由CSDN通过智能技术生成

It's somewhat common knowledge that Python functions can have a maximum of 256 arguments. What I'm curious to know is if this limit applies to *args and **kwargs when they're unrolled in the following manner:

items = [1,2,3,4,5,6]

def do_something(*items):

pass

I ask because, hypothetically, there might be cases where a list larger than 256 items gets unrolled as a set of *args or **kwargs.

解决方案

WFM

>>> fstr = 'def f(%s): pass'%(', '.join(['arg%d'%i for i in range(5000)]))

>>> exec(fstr)

>>> f

Update: as Brian noticed, the limit is on the calling side:

>>> exec 'f(' + ','.join(str(i) for i in range(5000)) + ')'

Traceback (most recent call last):

File "", line 1, in

exec 'f(' + ','.join(str(i) for i in range(5000)) + ')'

File "", line 1

SyntaxError: more than 255 arguments (, line 1)

on the other hand this works:

>>> f(*range(5000))

>>>

Conclusion: no, it does not apply to unrolled arguments.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值