
On Sun, Dec 4, 2022 at 11:08 AM Chris Angelico <rosuav@gmail.com> wrote:
You're not the first to try to use globals() for this, but it means that the context manager works ONLY at top-level.
I agree with most criticism of this proposal, although I'll note that the one place where I'd like something like this is at top level. I often write something like this at top level: __part1 = (some calculation) __part2 = (some other calculation) THING = combine(__part1, __part2) __part1 = __part2 = None If they are large objects and I forget to explictly delete the references, then they won't be garbage collected. Yes, this trivial example could be folded into a single line but that makes it much harder to understand what it's doing. And often those calculations are more complex and can't be written on one line. I can put that in a function which still leaves the function in scope: def __create_thing(): part1 = (some calculation) part2 = (some other calculation) return combine(part1, part2) THING = __create_thing() If we had a top-level-only local statement, I might use it but note that it's still clumsy since I have to make THING non-local: local: part1 = (some calculation) part2 = (some other calculation) nonlocal THING THING = combine(part1, part2) The often-rejected multi-line lambda might be better except those parens at the end are easy to miss: THING = (lambda: part1 = (some calculation) part2 = (some other calculation) return combine(part1, part2))() Looking at all these options, is the cost of adding anything actually worth the benefit? Probably not. --- Bruce