I wrote a line of code using lambda to close a list of file objects in python2.6:
map(lambda f: f.close(), files)
It works, but doesn’t in python3.1. Why?
Here is my test code:
import sys
files = [sys.stdin, sys.stderr]
for f in files: print(f.closed) # False in 2.6 & 3.1
map(lambda o : o.close(), files)
for f in files: print(f.closed) # True in 2.6 but False in 3.1
for f in files: f.close()
for f in files: print(f.closed) # True in 2.6 & 3.1
mapreturns a list in Python 2, but an iterator in Python 3. So the files will be closed only if you iterate over the result.Never apply
mapor similar “functional” functions to functions with side effects. Python is not a functional language, and will never be. Use aforloop: