Death to tuples!
Duncan Booth
duncan.booth at invalid.invalid
Mon Nov 28 09:48:35 EST 2005
Antoon Pardon wrote:
>> >>> def func(x):
>> ... if x in [1,3,5,7,8]:
>> ... print 'x is really odd'
>> ...
>> >>> dis.dis(func)
>> ...
>> 3 20 LOAD_FAST 0 (x)
>> 23 LOAD_CONST 2 (1)
>> 26 LOAD_CONST 3 (3)
>> 29 LOAD_CONST 4 (5)
>> 32 LOAD_CONST 5 (7)
>> 35 LOAD_CONST 6 (8)
>> 38 BUILD_LIST 5
>> 41 COMPARE_OP 6 (in)
>
> I'm probably missing something, but what would be the problem if this
> list was created during compile time?
Not much in this particular instance. 'x in aList' is implemented as
aList.__contains__(x), so there isn't any easy way to get hold of the
list[*] and keep a reference to it. On the other hand:
def func(x):
return x + [1, 3, 5, 7, 8]
we could pass in an object x with an add operator which gets hold of its
right hand operand and mutates it.
So the problem is that we can't just turn any list used as a constant into
a constant list, we need to be absolutely sure that the list is used only
in a few very restricted circumstances, and since there isn't actually any
benefit to using a list here rather than a tuple it hardly seems
worthwhile.
There might be some mileage in compiling the list as a constant and copying
it before use, but you would have to do a lot of timing tests to be sure.
[*] except through f.func_code.co_consts, but that doesn't count.
More information about the Python-list
mailing list