How do I return None instead of raising AttributeError?
Quinn Dunkan
quinn at seniti.ugcs.caltech.edu
Sun Sep 24 05:38:19 EDT 2000
More information about the Python-list mailing list
Sun Sep 24 05:38:19 EDT 2000
- Previous message (by thread): How do I return None instead of raising AttributeError?
- Next message (by thread): How do I return None instead of raising AttributeError?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Sun, 24 Sep 2000 05:07:57 GMT, Scott M. Ransom <ransom at cfa.harvard.edu> wrote: >Hello, > >I want a simple class that returns None if I try and access any >attribute that has not already been set. In other words, I want to >return a None instead of raising an AttributeError. [...] >>>> class test2: >... def __getattr__(self, name): >... try: return self.name >... except AttributeError: >... return None >... >>>> a = test2() >>>> a.b = 1.0 >>>> a.b >1.0 >>>> a.c >Segmentation fault > >Now a SegFault! Any idea what is happening here? (I am using Python >1.6 under Linux...) 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)
- Previous message (by thread): How do I return None instead of raising AttributeError?
- Next message (by thread): How do I return None instead of raising AttributeError?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list