Comparison with False - something I don't understand
MRAB
python at mrabarnett.plus.com
Sun Dec 5 21:01:24 EST 2010
On 05/12/2010 21:01, Martin v. Loewis wrote:
>> 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 your function returns a list when successful, it should not return
> False in the error case. Instead, it should return None (indicating that
> there is no list).
>
> Then the condition changes to
>
> result = myfunction()
> if result is None:
> # error condition
>
> Using None for "no result available" is very common in Python. Using
> False for the same purpose (i.e. returning either a list or False)
> is not. If you return False from a function, the only other possible
> result should be True.
>
As an example, the re module uses both two approaches.
If you ask it to compile a regex:
rgx = re.compile(regex)
it either returns a PatternObject (if the regex is valid) or raises an
exception (if the regex isn't valid).
If you ask it to search a string:
rgx.search(string)
it returns either a MatchObject (if the match is successful) or None
(if the match isn't successful).
More information about the Python-list
mailing list