functional programming with map()

Gerson Kurz gerson.kurz at t-online.de
Mon Feb 25 09:17:37 EST 2002


And then, there is always the braindead solution to choose from

------------------------ (cut here) ------------------------
import sys, os

# create a list of unique functions printing values
functions = [lambda x=i:sys.stdout.write("f(%d) called\n" % x) for i
in range(10)]

print "The easy way:"

for function in functions:
    function()

print "The braindead way:"

callem = lambda functions,l=[tempfile.mktemp()]:map(eval,\
('sys.stdout.write(str(l))','l.append(open(l[0],"w"))',
 'map(lambda x,l=l:l[1].write("functions[%d]()\\n"%x),'\
 'xrange(len(functions)))','l[1].close()','execfile(l[0])',
 'os.remove(l[0])'))

callem(functions)
------------------------ (cut here) ------------------------
The code creates a temporary file and then uses execfile() to execute
it. This is not threadsafe ;) I cannot use "exec" because thats a
statement & not allowed in lambda.

Note that I sense a slight problem with the scoping rules in the
callem code: the lambda in line 3 has to pass "l=l", otherwise the
code won't work. I have no idea why, because I was under the
impression that that is not necessary with those new rules. Go figure
it out ;)




More information about the Python-list mailing list