[Python-ideas] warn/error when using a method as boolean in ifs/whiles
Steven D'Aprano
steve at pearwood.info
Tue Oct 11 10:00:20 EDT 2016
On Tue, Oct 11, 2016 at 02:41:34PM +0200, Sven R. Kunze wrote:
> Hey python-ideas,
>
> on django-developers, an intriguing idea appeared:
> https://groups.google.com/d/msg/django-developers/4bntzg1HwwY/HHHjbDnLBQAJ
>
> """
> It seems to me that the default `method.__bool__` is undesirable in
> Jinja2 templates. I do not know Jinja2 well enough, but 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__`?
> This would solve the issue not just for the methods you mention, but
> more in general.
That should be easy enough to do as a custom descriptor.
But I would not like to see the default function or method __bool__
raise a warning. Consider processing a sequence of functions/methods,
skipping any which are None:
for func in callables:
if func is not None:
func(some_arg)
I often written code like that. Now imagine that somebody reasons that
since all functions and methods are truthy, and None if falsey, we can
write the code as:
for func in callables:
if func:
func(some_arg)
That's perfectly reasonable code too, and it should be purely a matter
of taste whether you prefer that or the first version. But with this
suggestion, we get flooded by spurious warnings.
So I think this is something that Django/Jinja2 should implement for its
own methods that need it, it should not be a general feature of all
Python functions/methods.
--
Steve
More information about the Python-ideas
mailing list