osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Tutor] beginning to code


On 09/13/2017 09:18 AM, ROGER GRAYDON CHRISTMAN wrote:
> I have not yet mastered how to respond to a particular note in a threadwith the
> mailer that I use, so this is not in response to anyone in particular,but just
> to some of the sentiments as a whole.
>>   if x:>      # do something
> Completely out of context, I would dislike it just because it is far too
> vague.Is it testing for zero?  for an empty list?  or for some object's
> completelyarbitrary definition of truthiness?

It is absolutely NOT vague, and the answer is Yes for all of the above.  It is well defined that 
ALL values can be used in a boolean sense.

Quoting the on-line Standard Library reference:
------------
4.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of 
the Boolean operations below.

By default, an object is considered true unless its class defines either a __bool__() method 
that returns False or a __len__() method that returns zero, when called with the object. [1] 
Here are most of the built-in objects considered false:

     constants defined to be false: None and False.
     zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
     empty sequences and collections: '', (), [], {}, set(), range(0)

Operations and built-in functions that have a Boolean result always return 0 or False for false 
and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or 
and and always return one of their operands.)
-------------

> but in context is another thing entirely.
> was x assigned to recently?   
Irrelevant, it uses whatever the current value is.

>                                is the type of x obvious so its truthiness is
> also obvious?Then fine -- if it is clear that x is a list, I'm happy to use
> this to test for an empty list.But if x is some other creation, like a user
> defined type, I would really prefer to seesomething analogous to:
> if not x.is_empty()     or    x.exists()     or    x.has_brain()
> And most definitely if x is assigned outside my control, I would definitely
> wantsome way to test or verify x's type before I start using it, lest my
> randomnumber generator with its
> (A + B * C) % D
> finds itself concatenating strings and formatting data.

Again irrelevant.  That's the beauty/bane of duck typing.  Learn to use it to your advantage and 
only check data types when it is absolutely necessary ? which is rarely!

> Roger Christman
> 

-- 
      -=- Larry -=-