Using 'in' with a Dict

Kartic kartic.krishnamurthy at gmail.com
Wed Feb 16 16:54:48 EST 2005


This is what I did ....

>>> import compiler
>>> exec1 = compiler.compile('''if "foo" in m:  print "sweet"''', '',
'exec')
>>> exec2 = compiler.compile('''if m.has_key("foo"):  print "dude"''',
'', 'exec')
>>> exec1.co_code
'd\x01\x00e\x00\x00j\x06\x00o\t\x00\x01d\x02\x00GHn\x01\x00\x01d\x00\x00S'
>>> exec2.co_code
'e\x00\x00i\x01\x00d\x01\x00\x83\x01\x00o\t\x00\x01d\x02\x00GHn\x01\x00\x01d\x00\x00S'
>>> exec2 = compiler.compile('''if m.has_key("foo"):  print "sweet"''',
'', 'exec')
>>> exec2.co_code
'e\x00\x00i\x01\x00d\x01\x00\x83\x01\x00o\t\x00\x01d\x02\x00GHn\x01\x00\x01d\x00\x00S'
>>> exec(exec2)
sweet
>>> exec(exec1)
sweet
>>> exec1.co_varnames
('m',)
>>> exec2.co_varnames
('m', 'has_key')
>>>

The code generated with the has_key() version is slightly large (3
bytes) than the one with the membership test. The co_varnames for the
two code objects vary, as the second one has the has_key method also,
which the other version does not.

Thanks,
-Kartic




More information about the Python-list mailing list