How do I return None instead of raising AttributeError?

Bernhard Herzog herzog at online.de
Sun Sep 24 07:22:56 EDT 2000


quinn at seniti.ugcs.caltech.edu (Quinn Dunkan) writes:

> Well, you've got the classic __getattr__ infinite recursion bug, but your
> python isn't behaving nicely about it (mine says 'Maximum recursion depth
> exceeded').  As far as solving your problem, this is sort of hackish, but it
> works, unless you want underscore attrs to not throw AttributeError, in which
> case you'll have to go to the ref guide and list out the special names:
> 
> class A:
>     def __getattr__(self, name):
>         if (name[:2] == '__' and name[-2:] == '__'
>                 and not self.__dict__.has_key(name)):
>             raise AttributeError, name
>         return self.__dict__.get(name)

Which can easily be simplified to:

class A:
    def __getattr__(self, name):
        if (name[:2] == '__' and name[-2:] == '__'):
            raise AttributeError, name
        return None

Because __getattr__ is only called when name is not in self.__dict__
self.__dict__.has_key(name) is always false and self.__dict__.get(name)
always returns None.


-- 
Bernhard Herzog   | Sketch, a drawing program for Unix
herzog at online.de  | http://sketch.sourceforge.net/



More information about the Python-list mailing list