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

Paul Moore p.f.moore at gmail.com
Tue Oct 11 09:59:47 EDT 2016


On 11 October 2016 at 14:38, Eric Snow <ericsnowcurrently at gmail.com> wrote:
> 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... :)

Certainly. But the whole point of the warning is to catch people who
do the wrong thing. All I'm saying is that the new warning would cause
problems for people who omit a (currently unnecessary) "is None" check
in the process of protecting people who forget whether an attribute is
a method or a property. Which group do we prefer to help?

As I said, I find false positives with warnings particularly annoying,
so personally I may find it less acceptable to ask people with working
code to tighten it up than others do. It's a trade-off (and although
"warns on correct code" is very close to a backward compatibility
break[1], I *do* think it's worth considering here - it's just that my
personal feelings are mixed).

Paul

[1] Technically it *is* a break. But I'm willing to give a little
wiggle room to the argument that "it's only a warning".


More information about the Python-ideas mailing list