Could we add __enter__ and __exit__ to the tuple type?

Look at the following code:


a = open('a.tmp', 'w')
b = open('b.tmp', 'w')

with (a, b) as (af, bf):
    af.write("1")
    bf.write("2")




Even better example:


with tuple(open(str(_n) + '.tmp', 'w') for _n in range(1000)) as f:
    for n, fn in enumerate(f):
        f.write(str(n))




Tuple as context manager would invoke __enter__ for each of its elements and return a tuple of the results.

On exit, the __exit__ method would be invoked for every element.


We could even generalize it to every kind of iterable.

This is somewhat consistent with treatment of exception types in 'except' clause.


try:
    something()
except Exception1 as error:
    handlerA(error)
except (Exception2, Exception3) as error:
    handlerB(error)



Tuple of exception types is accepted in 'except' clause, as well as a single exception type. We could apply that rule to the 'with' clause.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/QCYHV6FULSAIEUD2GQDG2LT6USP4N6DB/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to