Use cases for del

Grant Edwards grante at visi.com
Thu Jul 7 10:42:11 EDT 2005


On 2005-07-07, Ron Adam <rrr at ronadam.com> wrote:

>>    class demo:
>>       def foo(v=None):
>>           if v is not None:
>>               self.v = v
>>           return self.v   
>
> You are really checking if v exists, so having it undefined in
> namespace as the default is consistent with what you are
> doing.
>
> As I said above...
>
> >>>>It would be a way to set an argument as being optional without
> >>>>actually assigning a value to it.
>
> So it would still work like you expect even though v is not
> bound to anything.  Like I said the bigger problem is that
> globals will be visible and that would create a conflict.
> Setting a value to None in a function hides globals of the
> same name.  That wouldn't happen if None unbound names as del
> does.

Good point.  I hadn't thought of that.

> So you would need to use something else for that purpose I
> suppose, but that was why None became a literal in the first
> place, so maybe it's taking a step backwards.
>
>
>> 2) So I can use it as sort of a NaN equivalent.
>> 
>>    if self.fd is None:
>>       self.fd = os.open('foo.bar','w')
>>    
>>    if self.fd is not None:
>>       os.close(self.fd)
>>       self.fd = None      
>
> It would still work as you expect.  A while back I suggested an 'also' 
> for if that would do exactly that with only one test.  Nobody liked it.
>
>       if self.fd is None:
>          self.fd = os.open('foo.bar','w')
>          # do something with self.fd
>
>       also:
>          os.close(self.fd)
>          self.fd = None
>
>
>>>If a value isn't established yet, then do you need the name
>>>defined?
>>  
>> I find it more obvious to set the name to None during the
>> periods that it isn't valid than to delete it and check for a
>> NameError when I want to know if the value is usable or not.
>
> You would still be able to do that explicitly and it probably would be a 
> good idea when you aren't sure if a name is left over from something else.
>
> If a name is None, it means it's available and unassigned, so
> you don't have to check for a NameError.

How would you spell "if a name is None"?

Personally, I think the spellings

   del name
   if 'name' in locals()

is much more explicit/obvious than

   name = None
   name is None   

I expect the "=" operator to bind a name to a value.  Having it
do something completely different some of the time seems a bit
unpythonic.
   
-- 
Grant Edwards                   grante             Yow!  Today, THREE WINOS
                                  at               from DETROIT sold me a
                               visi.com            framed photo of TAB HUNTER
                                                   before his MAKEOVER!



More information about the Python-list mailing list