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

Sven R. Kunze srkunze at mail.de
Tue Oct 11 08:41:34 EDT 2016

Hey python-ideas,

on django-developers, an intriguing idea appeared: 

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.
[Or maybe Python itself should have that warning/error?]

Django implemented form.is_valid as a function. During development, 
people fall into the trap of believing it's a property or boolean 
attribute. That's usually not big deal but can take substantial amount 
of time when writing non trivial code among which reside following 
innocuous-looking lines:

if obj.has_special_property:
     # will always
     # be executed

What do you think about that Python emitting an warning/error as 
described above?


More information about the Python-ideas mailing list