Avoiding NameError by defaulting to None

Ron Adam rrr at ronadam.com
Wed Jul 6 21:26:38 CEST 2005

Scott David Daniels wrote:

> 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

Yep, I concede.  The problem is if undefined names return None, and None 
deletes a name,  then assigning a undefined name to an existing name, 
will delete it silently.

Definitely Not good!

So it should give an error as it currently does if an undefined name is 
used on the right side of an =.

It could still work otherwise to unbind names, and (undefined_name == 
None) could still be a valid way to check if a name is defined without 
using a try-except.

But it would definitely be a Python 3000 change as all the functions 
that return None would then cause errors.


More information about the Python-list mailing list