Use cases for del

Ron Adam rrr at ronadam.com
Thu Jul 7 14:24:41 EDT 2005


Steven D'Aprano wrote:

> Ron Adam wrote:
> 
>> Why would you want to use None as an integer value?
>>
>> If a value isn't established yet, then do you need the name defined? 
>> Wouldn't it be better to wait until you need the name then give it a 
>> value?
> 
> 
> Er, maybe I'm misunderstanding something here, but surely the most 
> obvious case is for default and special function arguments:
> 
> def count_records(record_obj, start=0, end=None):
>     if end == None:
>         end = len(record_obj)
>     if start == None:  # this is not the default!
>         # start at the current position
>         start = record_obj.current
>     n = 0
>     for rec in record_obj.data[start:end]:
>         if not rec.isblank():
>             n += 1
>     return n
> 
> which you call with:
> 
> # current position to end
> count_records(myRecords, None)
> # start to end
> count_records(myRecords)
> # start to current position
> count_records(myRecords, end=myRecords.current)


You have three possible outcomes,
    count all
    count range
    count using current index
        count range from beginning to current
        count range from current to end


The most consistent way to do this would be:


def count_records(record_obj, start=0, end=len(record_obj)):
     n = 0
     for rec in record_obj.data[start:end]:
         if not rec.isblank():
             n += 1
     return n


# current position to end
count_records(myRecords, myRecords.current)

# start to end
count_records(myRecords)

# start to current position
count_records(myRecords, end=myRecords.current)


Cheers,
Ron






More information about the Python-list mailing list