Optimising literals away

MRAB python at mrabarnett.plus.com
Wed Sep 1 18:59:49 CEST 2010

On 01/09/2010 14:25, Lie Ryan wrote:
> On 09/01/10 17:06, Stefan Behnel wrote:
>> MRAB, 31.08.2010 23:53:
>>> On 31/08/2010 21:18, Terry Reedy wrote:
>>>> On 8/31/2010 12:33 PM, Aleksey wrote:
>>>>> On Aug 30, 10:38 pm, Tobias Weber wrote:
>>>>>> Hi,
>>>>>> whenever I type an "object literal" I'm unsure what optimisation
>>>>>> will do
>>>>>> to it.
>>>> Optimizations are generally implentation dependent. CPython currently
>>>> creates numbers, strings, and tuple literals just once. Mutable literals
>>>> must be created each time as they may be bound and saved.
>>>>>> def m(arg):
>>>>>> if arg&  set([1,2,3]):
>>>> set() is a function call, not a literal. When m is called, who knows
>>>> what 'set' will be bound to? In Py3, at least, you could write {1,2,3},
>>>> which is much faster as it avoids creating and deleting a list. On my
>>>> machine, .35 versus .88 usec. Even then, it must be calculated each time
>>>> because sets are mutable and could be returned to the calling code.
>>> There's still the possibility of some optimisation. If the resulting
>>> set is never stored anywhere (bound to a name, for example) then it
>>> could be created once. When the expression is evaluated there could be
>>> a check so see whether 'set' is bound to the built-in class, and, if it
>>> is, then just use the pre-created set.
> What if the set is mutated by the function? That will modify the global
> cache of the set; one way to prevent mutation is to use frozenset, but
> from the back of my mind, I think there was a discussion that rejects
> set literals producing a frozen set instead of regular set.
I was talking about a use case like the example code, where the set is
created, checked, and then discarded.

More information about the Python-list mailing list