On Sat, Dec 12, 2020 at 11:42 AM Jonathan Crall <erotemic@gmail.com> wrote:
I'm not sure if this has been asked / suggested before.
I'm wondering if there is any interest in conditional or loop-based `with` statements. I think it could be done without a syntax change.
### Napkin proposal
Context managers could define `__if__` or `__for__`, and if those dunder methods were defined, then the `with` statement would either behave like a conditional or a loop.
If `__if__` was defined then
``` with Ctx(): print('hi') ```
would only print `hi` if `__if__` returned True. This doesn't require a syntax change.
This part has been proposed before: https://www.python.org/dev/peps/pep-0377/
The `__for__` variant would likely need a minor syntax change.
``` with item in Ctx(): print(item) ```
The `__for__` method is a generator that generates arguments of a loop. The item will be printed as many times as there are items generated by `__for__`.
Not sure that this one has, but it's basically just a context manager and a for loop, so I'm not really sure how much you'd gain over just using the two constructs independently, given that there'd then be massive confusion over "when should I use 'with item in thing' and when should I use 'for item in thing'?". For many use cases, it may be best to write the body as a function, which can then be called more than once. You can decorate a function in order to do whatever you like, and the return value from the decorator could be whatever stats you want to provide (there's no rule says that a function decorator has to return a function!). ChrisA