Implicit conversion to boolean in if and while statements

Serhiy Storchaka storchaka at gmail.com
Fri Feb 15 20:09:42 CET 2013


On 10.02.13 13:37, Steven D'Aprano wrote:
> Unfortunately, Python has a minor design flaw. One of the most common
> use-cases for sets is for membership testing of literal sets:
> 
> def example(arg):
>      if arg in {'spam', 'ham', 'eggs', 'cheese'}:
>          ...
> 
> Unfortunately, set literals create *mutable* sets, not frozensets. That
> means that the compiler wastes time and memory creating am over-allocated
> mutable set object. If set literals created immutable frozensets, there
> would be some nice opportunities for the compiler to optimize this
> use-case.

CPython 3.2 optimizes this special case and creates a constant frozenset.

$ echo "arg in {'spam', 'ham', 'eggs', 'cheese'}" | python3.2 -m dis -
  1           0 LOAD_NAME                0 (arg) 
              3 LOAD_CONST               5 (frozenset({'cheese', 'eggs', 'ham', 'spam'})) 
              6 COMPARE_OP               6 (in) 
              9 POP_TOP              
             10 LOAD_CONST               4 (None) 
             13 RETURN_VALUE         





More information about the Python-list mailing list