An easy one today:
import os, threading
def foo(s):
print s
for dir in os.listdir(os.getcwd()):
threading.Thread(target=lambda: foo(dir)).start()
What bug may cause this to print something other than the contents of the current directory?
Comments
print "Yrg'f fnl bf.yvfgqve(pjq)==['n', 'o']. Ba gur svefg eha guebhtu gur sbe ybbc, qve=='n', naq gur guernq vf fgnegrq. Vs nsgre gur guernq vf fgnegrq, ohg orsber vg trgf gb vaibxr sbb(qve) gur qve inevnoyr vf frg gb 'o' (orpnhfr gur ybbc vf eha gur frpbaq gvzr) gura sbb('o') jvyy or pnyyrq naq lbh'yy frr 'o\\ao\\a'".decode('rot13')
for dir in os.listdir(os.getcwd()):
threading.Thread(target=foo, args=(dir,)).start()
Is the right way to do it ? Then dir would be evaluated at the Thread creation.
lambda dir=dir: foo(dir)
OTOH, in this case there's already a standard way of passing arguments, as shown above.
using threading for output is a friend of lambda.
Harald Armin Massa notonblogger
How else would we say:
total_size = reduce( os.listdir(os.getcwd()), lambda a,x: a+os.stat(x).st_size,0 )
short, clear, and to the point