[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:02:59 EDT 2016


On 11 October 2016 at 13:41, Sven R. Kunze <srkunze at mail.de> wrote:
> maybe they could benefit
> from a patch where `if`-statements give a warning/error when the expression
> is a callable (with the default `FunctionType.__bool__`?
[...]
> What do you think about that Python emitting an warning/error as described
> above?

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)

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).

I'm not sure:

Pros:

- Catches an annoying and potentially hard to spot bug

Cons:

- Would trigger on certain reasonable coding patterns that aren't an error
- IMO, "false positives" in warnings are very annoying, particularly
in Python where they are runtime rather than compile-time, and so
affect the end user (if they aren't fixed in development)

Paul


More information about the Python-ideas mailing list