[Python-ideas] revisit pep 377: good use case?
Steven D'Aprano
steve at pearwood.info
Thu Mar 1 02:26:51 CET 2012
Craig Yoshioka wrote:
> with uncached('file') as file:
> if not file: return
>
> which isn't so bad, except it is overloading the meaning of file a bit, and
No, I don't agree with that. It is normal Pythonic idiom for objects to be
interpreted in a boolean concept. The only difference here is that sometimes
file will be (presumably) a file-like object, and sometimes it needs to be a
sentinel like None.
But this shouldn't disturb you: you have already suggested one possible
implementation would be for __enter__ to return a special value,
SkipWithBlock, to force skipping the block. That's fine: you can have this
functionality *right now*. All you need do is change the spelling from
SkipWithBlock to None, and use an explicit test inside the block rather than
an implicit test, and you're done.
Best of all, the use of an explicit test means you can do this:
with whatever('file') as file:
if file is None:
log('error')
else:
normal_processing()
which you can't do with your suggested implicit test-and-skip.
The fact that with blocks are not flow-control is a feature, not a bug.
> why shouldn't the with block be skippable?
It is skippable. Like every other code block, it is skippable by wrapping it
in flow-control code to decide whether or not to skip it.
--
Steven
More information about the Python-ideas
mailing list