properties & exceptions

Saveen Reddy [MSFT] saveenr at online.microsoft.com
Sun Apr 13 20:30:58 EDT 2003


I was suprised by a python behavior I saw concerning exceptions thrown when
accessing a class through a property. Essentially, I am seeing an unexpected
exception, one that implies the property doesn't exist when in fact it does.
I haven't found any docs that explain this behavior and so my questions are
(1) is this behavior "by-design"? and (2) Besides not using properties, is
there a workaround?

(I see this behavior in Python 2.2.1 and 2.2.2)

Example code:

class FOO :

 def __init__( self ) :
  self.__bar__ = "Hello World"

 def _getbar1( self ) :
  return self.__bar__

 def _getbar2( self ) :
  raise "TROUBLE!"
  return self.__bar__

 def bar3( self ) :
  raise "TROUBLE!"
  return self.__bar__

 bar1 = property ( _getbar1 )
 bar2 = property ( _getbar2 )

foo = FOO()

#------------------------
#The line below works as expected ...
#-----------------------

>>> foo.bar1
'Hello World'


#------------------------
# When the line below runs ... Hmm... An exception was
# raised, yes. But I didn't
# expect AttributeError. I
# expected to receive the exception I threw, not a different one
#-----------------------

>>> foo.bar2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: FOO instance has no attribute 'bar2'

#------------------------
# Below is call to a normal method which has the
# behavior I expected, i.e. I received the proper exception
#-----------------------

>>> foo.bar3()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "proptest.py", line 16, in bar3
    raise "TROUBLE!"
TROUBLE!

Any wisdom is appreciated.
-s






More information about the Python-list mailing list