How do I return None instead of raising AttributeError?

Scott M. Ransom ransom at cfa.harvard.edu
Sun Sep 24 01:07:57 EDT 2000


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.

Here is try number one:

>>> class test1:
...     def __getattr__(self, name):
...         if self.__dict__.has_key(name):
...             return self.name
...         else:
...             return None
... 
>>> a = test1()
>>> a.b = 1.0
>>> a.b
1.0
>>> a.c
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: call of non-function (type None)

This gives me (almost) the correct functionality except that I can't use
any of the default class methods!  The last line passes '__repr__' as
name, which isn't in __dict__ and so a None gets returned.

Try again:

>>> 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...)

Thanks for the help,

Scott

-- 
Scott M. Ransom                   Address:  Harvard-Smithsonian CfA
Phone:  (617) 495-4142                      60 Garden St.  MS 10 
email:  ransom at cfa.harvard.edu              Cambridge, MA  02138
GPG Fingerprint: 06A9 9553 78BE 16DB 407B  FFCA 9BFA B6FF FFD3 2989



More information about the Python-list mailing list