Hwy doesn't len(None) return zero ?
Stef Mientki
stef.mientki at gmail.com
Wed Jun 30 18:46:05 EDT 2010
On 30-06-2010 20:56, Gary Herron wrote:
> On 06/30/2010 11:39 AM, Stef Mientki wrote:
>> hello,
>>
>> I've lot of functions that returns their result in some kind of tuple / list / array,
>> and if there is no result, these functions return None.
>> Now I'm often what to do something if I've more than 1 element in the result.
>> So I test:
>>
>> if len ( Result ) > 1 :
>>
>> But to prevent exceptions, i've to write ( I often forget)
>> if Result and ( len ( Result ) > 1 ) :
>>
>> So I wonder why len is not allowed on None
>> and if there are objections to extend the len function .
>>
>> thanks,
>> Stef Mientki
>
>
> Because the natural interpretation of len only makes sense for concepts such as a container or
> collection. The value None is no such thing. Assigning a meaning to len(None) begs the question
> of meanings for len(True), len(False), len(3.14), len(sys), ... This is a slippery slope, best
> avoided.
>
> But there are solutions:
>
> 1. Have your functions return [] or () or whatever. If they are to return a list, and the list
> may be empty, [] is correct.
>
thanks guys,
I think that will be the best idea.
cheers,
Stef
> 2. If you insist on a function returning a list sometimes and other values at other times (such
> as None), then be prepared to write your code which uses the result with test to determine which
> type was returned. Fortunately that's not hard, as your one example shows.
>
> 3. Create a test function Empty(Result) which does what you want returning a boolean and write
> your tests as:
> if Empty(Result): ...
>
> Gary Herron
>
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100701/4431002b/attachment-0001.html>
More information about the Python-list
mailing list