I'm using a namedtuple to hold sets of strings and their corresponding values. I'm not using a dictionary, because I want the strings accessible as attributes.
Here's my code:
from collections import namedtuple
# Shortened for readability :-)
strings = namedtuple("strings", ['a0', 'a1', 'a2', ..., 'a400'])
my_strings = strings(value0, value1, value2, ..., value400)
Ideally, once my_strings
is initialized, I should be able to do this:
print(my_strings.a1)
and get value1
printed back.
However, I get the following error instead:
strings(value0, value1, value2, ...value400)
^SyntaxError: more than 255 arguments
It seems python functions (including namedtuple's init()), do not accept more than 255 arguments when called. Is there any way to bypass this issue and have named tuples with more than 255 items? Why is there a 255 arguments limit anyway?
This is a limit to CPython function definitions; in versions before Python 3.7, you cannot specify more than 255 explicit arguments to a callable. This applies to any function definition, not just named tuples.
Note that this limit has been lifted in Python 3.7 and newer, where the new limit is
sys.maxint
. See What is a maximum number of arguments in a Python function?It is the generated code for the class that is hitting this limit. You cannot define a function with more than 255 arguments; the
__new__
class method of the resulting class is thus not achievable in the CPython implementation.You'll have to ask yourself, however, if you really should be using a different structure instead. It looks like you have a list-like piece of data to me; 400 numbered names is a sure sign of your data bleeding into your names.
You can work around this by creating your own subclass, manually:
This version of the named tuple avoids the long argument lists altogether, but otherwise behaves exactly like the original. The somewhat verbose
__new__
method is not strictly needed but does closely emulate the original behaviour when arguments are incomplete. Note the construction of the_fields
attribute; replace this with your own to name your tuple fields.Pass in a generator expression to set your arguments:
or if you have a list of values:
Either technique bypasses the limits on function signatures and function call argument counts.
Demo: