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

Paul Moore p.f.moore at gmail.com
Tue Oct 11 14:22:15 EDT 2016


On 11 October 2016 at 17:21, David Navarro <davisein at gmail.com> wrote:
> Something like this
>
> In [1]: def a(): pass
> In [2]: def r(): raise RuntimeError('Do not forget to call this')
> In [3]: a.__bool__ = r
> In [4]: if a: pass
>
> I don't have an environment to test if this is possible. This would allow
> marking with a decorator functions that might be misleading or that are a
> common source of issues for new users.

It would need to be somewhat more complex (the above doesn't work as
it stands, because __bool__ is only recognised as a method on a class,
not an attribute of a function). But it's doable, either manually
(make a a class with __call__ and __bool__) or semi-automatically (a
decorator that creates a class for which __call__ is defined as
running the decorated function, and __bool__ raises a warning).

Paul


More information about the Python-ideas mailing list