[Python-ideas] Automatic context managers
David Mertz
mertz at gnosis.cx
Fri Apr 26 22:12:26 CEST 2013
On Apr 26, 2013, at 12:46 PM, Bruce Leban wrote:
> On Fri, Apr 26, 2013 at 12:37 PM, David Mertz <mertz at gnosis.cx> wrote:
> I'd note that there's no reason you couldn't use the so-called "automatic context manager" already, it's just a matter of writing your own function rather than the built-in 'open()'. So, e.g. with a few lines of definition, you might use:
>
> boolean = SafeOpen(resource).use()
>
> I'd like to see those few lines if they are indeed possible. I don't see how the function would know when to call __exit__. It has to be after use() finishes.
You might get really perverse with stack inspection and whatnot. But I was thinking more of just a proxy method that introduced the safety.
class SafeOpen(object):
def __init__(self, resource):
self.resource = resource
def __getattr__(self, name):
def f(*args, **kws):
with open(self.resource) as x:
y = getattr(x, name)(*args, **kws)
return y
return f
--
If I seem shortsighted to you, it is only because I have stood on the backs of midgets.
More information about the Python-ideas
mailing list