[Python-3000] Set literal

"Martin v. Löwis" martin at v.loewis.de
Fri Jan 25 07:25:36 CET 2008


> But getting back to the original issue, what does using frozensets
> gain you over using a tuple:
> 
> if urlext in ('html', 'xml', 'php'):
> 
> Given that tuples are also immutable, couldn't the peepholer also
> optimize the tuple as a compile time constant?

py> def f():
...   if urlext in ('html','xml','php'):return 3
...
py> dis.dis(f)
  2           0 LOAD_GLOBAL              0 (urlext)
              3 LOAD_CONST               5 (('html', 'xml', 'php'))
              6 COMPARE_OP               6 (in)
              9 JUMP_IF_FALSE            8 (to 20)
             12 POP_TOP
             13 LOAD_CONST               4 (3)
             16 RETURN_VALUE
             17 JUMP_FORWARD             1 (to 21)
        >>   20 POP_TOP
        >>   21 LOAD_CONST               0 (None)
             24 RETURN_VALUE


> Since this idiom is
> usually used as a shortcut for:
> 
> if urlext == 'html' or urlext == 'xml' or urlext == 'php':
> 
> the semantics of using a frozenset are subtly different since with the
> equivalent tuple you know the search is linear and short circuits on
> success, but using a frozenset the search order is undefined.  Of
> course if you had a largish search set, frozenset would probably be
> quicker than using a tuple, but I think it's safe to say the search
> set is small for the typical case.

Are you implying that the search is faster for a tuple if the set is
small?

Regards,
Martin


More information about the Python-3000 mailing list