Avoiding NameError by defaulting to None

Scott David Daniels Scott.Daniels at Acm.Org
Wed Jul 6 13:47:42 EDT 2005


Ron Adam wrote:
> Dan Sommers wrote:
>> Lots more hard-to-find errors from code like this:
>>     filehandle = open( 'somefile' )
>>     do_something_with_an_open_file( file_handle )
>>     filehandle.close( )
> 
> If do_something_with_an_open_file() is not defined. Then you will get:
>     TypeError: 'NoneType' object is not callable
> 
> 
> If "file_handle" (vs "filehandle") is None.  Then you will still get an 
> error as soon as you tried to use the invalid file handle.
Ah, but where you use it can now far from the error in the source.  The
None could get packed up in a tuple, stored in a dictionary, all manner
of strange things before discovering it was an unavailable value.  I
would love the time back that I spent chasing bugs when Smalltalk told
me (I forget the exact phrasing) "nil does not respond to message abc."
My first reaction was always, "of course it doesn't, this message is
useless."  You really want the error to happen as close to the problem
as possible.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list