[Python-ideas] warn/error when using a method as boolean in ifs/whiles

Eric Snow ericsnowcurrently at gmail.com
Tue Oct 11 09:38:23 EDT 2016


On Tue, Oct 11, 2016 at 7:02 AM, Paul Moore <p.f.moore at gmail.com> wrote:
> Interesting idea. There may be some issues - consider an object that
> may optionally have a handler method handle_event, and you want to
> call that method if it exists:
>
>     handler = getattr(obj, 'handle_event', None)
>     if handler:
>         # prepare arguments
>         handler(args)

This isn't a problem if you test for None:  "if handler is not None".
I was going to concede that there are probably other cases where that
doesn't help, but can't think of any.  In what case would a callable
also evaluate to False, or you have a collection of arbitrary mixed
values and you are testing their truthiness?  So perhaps always using
a None test is the correct answer if we add the warning.  That said, I
have no illusions that I know all possible use cases... :)

>
> That could would break (technically, it would produce an incorrect
> warning) with this change.
>
> I do think that the scenario you described is a valid one - and
> there's no obvious "better name". The stdlib module pathlib uses the
> same pattern "my_path.is_absolute()", and IIRC I've made the mistake
> you described (although I don't recall any major trauma, so the
> problem was probably fixed relatively quickly).

FWIW, I do the same thing from time to time and I usually only catch
it when writing unit tests.  I'm +1 to a warning as proposed.

-eric


More information about the Python-ideas mailing list