If you don't understand why a construct doesn't work, neither will the next person who has to read your code. If you mean
b = 1
you should say that. In this case vars()
gives you access to the function local dictionary so your code is equivalent to
def a():
b = 1
where b
is local to a
and evaporates when it goes out of scope upon exit from a
.
premature optimization is the root of many people's attempt to second-guess Python
from itertools import izip
import timeit
import msw.wordlist
def zip_list(p):
"""construct a dictionary of length 100 from a list of strings"""
return dict(zip(p[:100], p[100:]))
def izip_list(p):
"""as zip_list but avoids creating a new list to feed to dict()"""
return dict(izip(p[:100], p[100:]))
def pass_list(p):
"""take 100 elements of a list and do nothing"""
for i in p[:100]:
pass
def exec_pass_list(p):
"""exec() a no-op 100 times"""
for i in xrange(100):
exec('pass')
# returns a list of 64'000 unique lowercase dictionary words for tests
words = msw.wordlist.Wordlist()
words.shuffle()
words = words[:200]
print 'words', words[:5], '...'
for func in ['zip_list', 'izip_list', 'pass_list', 'exec_pass_list']:
t = timeit.Timer('%s(words)' % func,
'from __main__ import words, %s' % func)
print func, t.repeat(number=10**5)
which yields:
words ['concatenated', 'predicament', 'shtick', 'imagine', 'stationing'] ...
zip_list [1.8603439331054688, 1.8597819805145264, 1.8571949005126953]
izip_list [1.5500969886779785, 1.5501470565795898, 1.5536530017852783]
pass_list [0.26778006553649902, 0.26837801933288574, 0.26767921447753906]
exec_pass_list [74.459679126739502, 75.221366882324219, 77.538936853408813]
I didn't bother trying implement whatever the OP was trying to do because being 50 times slower to not construct a dictionary sort makes further testing kinda stupid.