Implicit conversion to boolean in if and while statements

Rick Johnson rantingrickjohnson at gmail.com
Fri Feb 8 00:16:39 EST 2013


On Monday, July 16, 2012 7:43:47 PM UTC-5, Steven D'Aprano wrote:
> 
> [...] 
> 
> If I insist on making a single object do duty for both the jar and the 
> jellybean count, then I need a "null jar object", and I probably end up 
> with something like this:
> 
> Jar(number_of_beans=None) => null jar object with jar.jellybeans = 0
> Jar(number_of_beans=0) => normal jar object with jar.jellybeans = 0
> Jar(number_of_beans=42) => normal jar object with jar.jellybeans = 42
> 
> and then my code becomes even more complicated and less understandable, 
> but hey, it's *my* code and I can do whatever damn-fool thing I like!

Indeed, but why would you create a jellybean jar and never put any jelly beans into the jar? If you are doing so because you want to loop over a number of objects and never get a NameError than you need to study up on a few language features you may be unaware of:

 1. block: try/except
 2. statement: if
 3. function: hasattr(obj, name)
 
Creating /any/ object that is never utilized is code smell; I don't care how extravagant your explanations are either -- and boy did you go to some great efforts to explain this line of argument. I'm impressed! ;-)



More information about the Python-list mailing list