"if x == None" raises "'NoneType' object is not callable"

Peter Hansen peter at engcorp.com
Mon Sep 16 15:20:04 CEST 2002


Luc Saffre wrote:
> """
> If I define __getattr__() and __setattr__() for a class, then I cannot
> test instances of this class for equality with None.
> 
> the code example below raises
> TypeError: 'NoneType' object is not callable
> 
> class Row:
> 
>    def __init__(self):
>       self.__dict__["_values"] = {}
> 
>    def __getattr__(self,name):
>       try:
>          return self._values[name]
>       except KeyError,e:
>          AttributeError,str(e)
>    
>    def __setattr__(self,name,value):
>       self.__dict__["_values"][name] = value
> 
> 
> row = Row()
> if row == None: # here it happens.
>    print "row instance is None!"

When when you call "row == None" it calls __getattr__ with '__eq__'
to see if you want to provide a equality comparator function.
Inside __getattr__ you are not going to find such a beast,
so you go to the exception handler.  Unfortunately, you left
out the "raise" keyword, so you are in the end returning None
as all methods do in Python which don't explicitly return something
else.

-Peter




More information about the Python-list mailing list