Implicit conversion to boolean in if and while statements

Ethan Furman ethan at
Tue Jul 17 14:35:52 CEST 2012

Andrew Berg wrote:
> To put it in duck-typing terms, why should everything have to quack like
> True or False? Sure, I can see why 1 quacks like True or [] quacks like
> False, but I don't see why say, a Logger or function should quack like
> either. Should a Thread object be True if it's been started and False
> otherwise?

True and False are red herrings.  It is more appropriate to think that 
True quacks like something and False like nothing than the other way 'round.

Maybe some examples from my own code will help:

DbfTable    --> True if any records in table, False otherwise

DbfIndex    --> True if any records in index, False otherwise

DbfList     --> True if any records in list, False otherwise

DbfDate     --> True if a date, False otherwise (could be eight spaces 
instead of a real date)

DbfDateTime --> True if a datetime, False otherwise

DbfRecord   --> True always

DbfRecordTemplate --> True always

DbfRecordVaporware --> False always

While I could have DbfRecord be False if, for example, it had no data 
stored in it, I have no use case for that scenario so haven't bothered. 
  Also, at this point I am using the distinction of True/False with 
regards to records to determine if I have a real record (True means a 
record/template I can read/write, False means I don't).

> If it truly is about something vs. nothing, why is a NameError (or
> AttributeError) raised when testing with an undefined variable? Being
> undefined quacks like nothing, doesn't it?

It's about /representing/ something vs. nothing. An undefined name isn't 
representing anything (except a bug, of course ;).


More information about the Python-list mailing list