(original) (raw)
On 24 November 2017 at 01:49, Barry Warsaw <barry@python.org> wrote:
The conceptual delta between knowing how to call "noop()" and how to write "def noop(): pass" is just a \*teensy\* bit smaller than that between knowing how to use:
On Nov 22, 2017, at 19:32, Victor Stinner <victor.stinner@gmail.com> wrote:
\>
\> Aha, contextlib.nullcontext() was just added, cool!
So, if I rewrite PEP 559 in terms of decorators it won’t get rejected?
with nullcontext(value) as var:
...
and how to write:
@contextlib.contextmanager
def nullcontext(enter\_result):
yield enter\_result
or:
class nullcontext(object):
def \_\_init\_\_(self, enter\_result):
self.enter\_result = enter\_result
def \_\_enter\_\_(self):
return self.enter\_result
def \_\_exit\_\_(self, \*args):
pass
So the deciding line for me was "Should people need to know how to write their own context managers in order to have access to a null context manager?", and I eventually decided the right answer was "No", since the context management protocol is actually reasonably tricky conceptually, and even the simplest version still requires knowing how to use decorators and generators (as well as knowing which specific decorator to use).
The conceptual step between calling and writing functions is much smaller, and defining your own re-usable functions is a more fundamental Python skill than defining your own context managers.
And while I assume you were mostly joking, the idea of a "@functools.stub\_call(result=None)" decorator to temporarily replace an otherwise expensive function call could be a genuinely interesting primitive. \`unittest.mock\` and other testing libraries already have a bunch of tools along those lines, so the principle at work there would be pattern extraction based on things people already do for themselves.