3 ms·
The variable isn't necessary, and contextlib.contextmanager is the standard wrapper for arbitrary functions. Here's the example code from the documentation:
by eesmith 9y ago
The variable isn't necessary, and contextlib.contextmanager is the standard wrapper for arbitrary functions. Here's the example code from the documentation:
from contextlib import contextmanager
@contextmanager
def tag(name):
print "<%s>" % name
yield
print "</%s>" % name
>>> with tag("h1"):
... print("foo")
...
<h1>
foo
</h1>
- tedunangst 9y agoBut how does that close over other locals? I'll admit I haven't looked too closely, but go defer makes it pretty easy to drop in a lambda. Getting stuff into your decorated functions by reference is going to be awkward, unless I'm missing something.
- eesmith 9y agoI'll need to see an example to understand the issue. The idioms between the two languages are different enough that idiomatic Go might be written a different way for idiomatic Python. Remember, "with" isn't always required - you can also write the code using a try/finally.
- masklinn 9y ago> But how does that close over other locals? It does not, it works like a C++ destructor, the context management code is static, and anything it needs is provided as a parameter. While "ad-hoc" context managers are possible (and quite trivial in fact): 1. I don't remember ever wanting one 2. they would not be convenient owing to Python's limited lambdas so 3. you'd probably implement them using a ~decorator on a nested function instead which 4. may look quite odd to most Python developers