Expression can be simplified on list

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Sep 14 00:47:15 EDT 2016


On Wednesday 14 September 2016 12:16, Lawrence D’Oliveiro wrote:

> On Tuesday, September 13, 2016 at 2:33:40 PM UTC+12, Ned Batchelder wrote:
>> Why do you object to the type conversion to bool?
> 
> It would be better if all such conversions were explicit, e.g.
> 
>     if bool(«non-bool expr») :
>     if not bool(«non-bool expr») :
> 
> instead of
> 
>     if «non-bool expr» :
>     if not «non-bool expr» :


Better according to what standard?

According to statically-typed languages, it's not just better, but probably 
essential, to explicitly cast or coerce values to bool.

But according to dynamically-typed languages like Python, using the second pair 
of examples is just duck-typing, where all values and objects can "quack like a 
bool". There's no need to explicitly cast an expression to bool, because the 
interpreter can do it for you as part of the truthiness protocol. Needing 
explicit casts, as you do, is as silly as these would be:


for obj in iter(expression):
    ...


# hypothetical built-in to convert methods to callables
result = callable(myobj.method)(arg)


only *even more so*, since implicit truthiness is expected to always succeed, 
while iter() is not.


You're perfectly entitled to dislike duck-typed truthiness. But that makes the 
majority of dynamically-typed languages (like Python, Javascript, Ruby, Lua and 
more) a bad fit for your way of thinking.



-- 
Steven
git gets easier once you get the basic idea that branches are homeomorphic 
endofunctors mapping submanifolds of a Hilbert space.




More information about the Python-list mailing list