[Python-Dev] Re: 3.10 change (?) for __bool__

2021年1月12日 09:26:55 -0800

On 1/12/21 10:53 AM, Mark Shannon wrote:
> Hi everyone,
>
> Should the optimizer eliminate tests that it can prove have no effect
> on the control flow of the program, even if that may eliminate some
> side effects in __bool__()?
>
> For several years we have converted
>
>   if a and b:
>     ...
>
> to
>
>   if a:
>     if b:
>       ...
>
> which are equivalent, unless bool(a) has side effects the second time
> it is called.
>
> In master we convert `if x: pass` to `pass` which is equivalent,
> unless bool(x) has side effects the first time it is called. This is a
> recent change.
>
> This is one of those "easy to fix, if we can decide on the semantics"
> bugs.
>
>
> Submit your thoughts to https://bugs.python.org/issue42899, please.
>
> Cheers,
> Mark. 
One key point about 'and' and 'or' is that those operators are defined
to be 'short circuiting', i.e. that with a and b, that if a is false,
then b is not evaluated at all. This can be important if a is a
condition that test if the expression b is 'safe' to evaluate. In fact,
isn't it true that 'a and b' is defined to be the equivalent to: 'a if
not a else b' so b doesn't need to be evaluated unless a is truthy.
I know that I would be very surpised if a statement like
if foo():
  pass
ended up optimizing itself and not calling foo(), which is only one step
away from the quoted case of
if b:
  pass
which is the equivalent to
if b.__bool__():
  pass
Yes, perhaps there is more of an expectation that __bool__() is
innocuous, but is that a an assumption that should be baked into the
language.
-- 
Richard Damon
_______________________________________________
Python-Dev mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/[email protected]/message/HODNO42SFFRFX4IJY5K562YHT2MTIHIQ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to