4 ms·
Python actually does have a kind of "anonymous function" feature, at least in a way that replaces most common use cases. It just happens to be bundled in a uniq
by developer2 9y ago
Python actually does have a kind of "anonymous function" feature, at least in a way that replaces most common use cases. It just happens to be bundled in a unique Python-like way. A lot of people don't seem to know about @contextmanager (contextlib.contextmanager) - it's what provides the functionality for "with" blocks. You've probably seen with() used with file operations (open file, run block of code, file is closed automatically at end of block), but I suspect many developers are unaware that you can create your own context managers.
While they are not true anonymous functions, I have yet to stumble on a scenario where a context manager did not fit the bill. They're easy to create - nothing more than a try/except/finally with a "yield" call to execute... you guessed it, essentially an anonymous function block. It's a little mind-warping the first time through, but it winds up creating clean code. PEP 343 is a good source to learn more.
- joshuamorton 9y agoHow do contextmanagers (which by the way, @contextmanager is sugar for manually defining an object with __enter__ and __exit__ methods) take the place of anonymous functions?