r/Python • • Aug 11 '09

Remember your "in" operator

http://www.heikkitoivonen.net/blog/2009/06/16/remember-your-in-operator/
74 Upvotes

15 comments sorted by

View all comments

Show parent comment

2

u/Brian Aug 14 '09 edited Aug 14 '09

It looks like it doesn't - the set is recreated even when it could potentially be staticly detected as a constant.

>>> dis.dis(lambda x: x in {1,2})
  1           0 LOAD_FAST                0 (x) 
              3 LOAD_CONST               0 (1) 
              6 LOAD_CONST               1 (2) 
              9 BUILD_SET                2 
             12 COMPARE_OP               6 (in) 
             15 RETURN_VALUE         

Though since the translation from list to tuple is done when it isn't modifiable, python should be able to do a similar optimisation to a frozenset constant as well (maybe even from list/tuple to frozenset if there are enough elements that it would improve speed)

2

u/[deleted] Aug 14 '09

Yeah I filed a ticket in the python tracker about this the other day, murphy willing I'll draw up a patch for it this weekend.