On Fri, Dec 11, 2020 at 07:41:27PM -0500, Jonathan Crall wrote:
If `__if__` was defined then
``` with Ctx(): print('hi') ```
would only print `hi` if `__if__` returned True. This doesn't require a syntax change.
How do you pass arguments to the "if" dunder? A generalised conditional context manager would look like this: if condition: with Ctx(*args) as obj: block With your suggested syntax, the condition has to be hard-coded into the `__if__` dunder. That's an extremely inflexible API. It also makes it hard to reason about your code, by burying a conditional if deep into the bowels of the context manager. Quick, if this code safe or not? with nuke(target='Woolloomooloo'): fire_missiles() Pity the poor people of Woolloomooloo (which is a real place, in Australia). They have no way of knowing whether or not the missiles are on the way. An explicit test is more flexible, easier to reason about, and much more readable. You suggested: >>> with ub.Cacher('name', cfgstr=ub.hash_data('dependencies')) as cacher: ... data = 'mydata' That looks all the world like data is unconditionally being over-written. The test `data is None` is invisible, and has to be built-into the ub.Cacher class, including the name "data". -- Steve