Comparison with False - something I don't understand
Harishankar
v.harishankar at gmail.com
Thu Dec 2 10:34:31 EST 2010
On Thu, 02 Dec 2010 10:19:35 -0500, Steve Holden wrote:
> On 12/2/2010 9:13 AM, Harishankar wrote:
>> On Thu, 02 Dec 2010 22:19:25 +1100, Ben Finney wrote:
>>
>>> More details of the problem you're trying to solve would help with
>>> giving specific advice.
>>
>> I'm writing functions with multiple points of failure exits. I use
>> return False as a way to flag the error condition rather than raising
>> exceptions. But under certain circumstances, the function can also
>> return empty lists which equate to false when using the condition like:
>>
>> # myfunction () can return a list of tuples, but can also return an
>> empty # list under certain conditions since it's query a database and
>> the result # can be empty also
>>
>> result = myfunction (vars)
>>
>> if not result:
>> # error condition
>>
>> Now above I first realized that the function can also return an empty
>> list under some conditions and so changed it to
>>
>> if result == False:
>> # error condition
>>
>>
>> But now I realize that it's better to use "is"
>>
>> if result is False:
>> # error condition
>>
>> That is how my problem arose.
>>
> Did you think about using exceptions to handle exceptional conditions?
> If you are new to Python it may not be the obvious soltuion, but it can
> greatly simplify program logic.
>
> regards
> Steve
I am not new to Python but I am not a fan of exceptions either. I prefer
to avoid writing my own exceptions because it feels too heavy and clunky
for simple error checking. Most times I find simple error checking ample
for my purposes.
Of course, I use the built-in exception objects when I have no choice,
but I hate try blocks. They add clunkiness to code and besides exception
objects seem to be fairly heavy-duty for simple error conditions where a
true/false flag would probably suffice.
I am also wary of using larger catch-all try blocks or try blocks with
multiple exception exits (which seem to make tracking subtle bugs
harder). I prefer the philosophy of dealing with errors immediately as
they arise, rather than delegate them to exception mechanism. Of course,
I could wrap single statements in try blocks, but that makes the code
even messier without any significant benefits.
--
Harishankar (http://harishankar.org http://lawstudentscommunity.com)
More information about the Python-list
mailing list