Could not close file functionally in python3.1?

I wrote a line of code using lambda to close the list of file objects in python2.6:

map(lambda f: f.close(), files)

It works but does not work 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
+5
source share
2 answers

map returns a list in Python 2, but an iterator in Python 3. That way, 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 never will be. Use a loop for:

for o in files:
    o.close()
+6
source

Python 3 - . :

, , .

. Python 2, map(f, seq) [f(i) for i in seq], Python 3 (f(i) for i in seq) - , . , . Ergo, ( : , !) for.

+4

All Articles