I've been thinking for a while that it would be good to be able to use context
managers in an expression context, and I haven't been able to come up with any
arguments against it (although it may not be to everyone's taste) and I can't
see any sign that it's come up before (although the words of it don't make very
specific search terms).
My suggestion is that a "with" clause could be written after an expression
(consistent with the conditional operator being written with "if" after the
first expression).
In general, this would be:
a(b) with c(d) as b
or it could allow multiple context managers:
a(b, c) with d(e) as b, f(g) as c
My original motivating example was this:
if name.startswith("https://"):
data = requests.get(name).json()
else:
with open(name) as stream:
data = json.load(stream)
which I'd much rather be able to write with a single expression:
data = (requests.get(name).json()
if name.startswith("https://")
else (json.load(stream)
with open(name) as stream))
It would behave just like a "with" statement, but pass a value / values back.
I don't think there would be any backward-compatibility issues with this.
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/FTCZBF34HYUKOOUTFFJZBTNXBTZRMWX4/
Code of Conduct: http://python.org/psf/codeofconduct/