Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is python "RAII" idiom for a variable number of resources?

What is the "best" way to open a variable number of files in python?

I can't fathom how to use "with" if the number of files is not known before-hand.

(Incoming from RAII/C++)

like image 388
user1174648 Avatar asked Oct 18 '25 15:10

user1174648


2 Answers

Well, you could define your own context manager that took a list of (filename, mode) pairs and returned a list of open file handles (and then closed all of those handles when the contextmanager exits).

See http://docs.python.org/reference/datamodel.html#context-managers and http://docs.python.org/library/contextlib.html for more details on how to define your own context managers.

like image 68
Amber Avatar answered Oct 21 '25 06:10

Amber


With 3.3, contextlib.ExitStack is now available for situations such as this. Here's some example code from the contextlib documentation:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

2.7 users are out of luck. Yet another reason to upgrade.

like image 27
Kevin Avatar answered Oct 21 '25 04:10

Kevin