[Python-ideas] if <expression> as <variable>
Steven D'Aprano
steve at pearwood.info
Thu Sep 7 12:25:39 EDT 2017
On Thu, Sep 07, 2017 at 04:36:40PM +0200, Jason H wrote:
> I also often wonder why we are left doing an assignment and test. You have two options:
> 1. assign to a variable then test and use
> 2. repeat the function call
Personally, I don't see what's wrong with the "assign then test" idiom.
x = something()
if x:
do_stuff()
> I would offer that 'with' [sh|c]ould be used:
> with test() as x:
> handle_truthy(x)
> else:
> handle_falsey() # do we provide x here too? Because None vs False?
This would cause confusing errors and mysterious behaviour, depending on
whether the test() object was a context manager or not. Which should
take priority? If you see:
with spam() as x:
do_stuff
is that a context manager with block (like "with open(...) as f") or
your boolean if test in disguise?
Having "with" sometimes be a disguised "if" and sometimes a regular
"with" will make it really, really hard to reason about code.
--
Steve
More information about the Python-ideas
mailing list