On Tue, Feb 28, 2012 at 1:04 PM, Craig Yoshioka <crai...@me.com> wrote: > > I see that there was previously a PEP to allow the with statement to skip the > enclosing block... this was shot down, and I'm trying to think of the most > elegant alternative. > The best I've found is to abuse the for notation: > > for _ in cachingcontext(x): > # create cached resources here > # return cached resources > > I would have really liked: > > with cachingcontext(x): > # create cached resources here > # return cached resources > > I'd also like to avoid the following because it is unnecessary boilerplate: > > with cachingcontext(x) as skip: > if not skip: > # create cached resources here > # return cached resources >
An alternative way to do this would be to make it a decorator. Something along the lines of (written in my browser): def cachedfunc(func): cachedvalue = None def newfunc(*args, **kwargs): nonlocal cachedvalue if cachedvalue is None: cachedvalue = func(*args, **kwargs) return cachedvalue return newfunc @cachedfunc def test(): import time time.sleep(1) return 10 test() # should take 1 second test() # should be instant While that formula has limitations, it shows the basis of the idea. I'll leave it to the reader to expand it to allow calls with different arguments producing different results. > > > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list