In [1]:
import re

In [2]:
class Foo(object):
    @property
    def bar(self):
        return self.x
    
    @bar.setter
    def bar(self, x):
        self.x = 3 * x

In [3]:
foo = Foo()
foo


Out[3]:
<__main__.Foo at 0xb41f778c>

In [4]:
foo.bar = 'world'

In [5]:
foo.bar


Out[5]:
'worldworldworld'

In [6]:
goo = Foo()
goo


Out[6]:
<__main__.Foo at 0xb41f9b6c>

In [7]:
goo.bar


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-786048e0efcd> in <module>()
----> 1 goo.bar

<ipython-input-2-1a22899dc137> in bar(self)
      2     @property
      3     def bar(self):
----> 4         return self.x
      5 
      6     @bar.setter

AttributeError: 'Foo' object has no attribute 'x'

The error message above is not helpful for coder, so starting with cell #9, I play with changing it to complain about 'bar' instead of complaining about 'x'.


In [8]:
goo.foo


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-c1979b4dcb61> in <module>()
----> 1 goo.foo

AttributeError: 'Foo' object has no attribute 'foo'

In [9]:
class Hoo(object):
    @property
    def bar(self):
        try:
            return self.x
        except AttributeError as e:
            # print('old e.args', repr(e.args))
            e.args = (re.sub(
                r"'[A-Za-z_][A-Za-z0-9_]*'$",
                "'bar'",
                e.args[0]), )
            e.args = (
                "{class_name!r} "
                "object has no attribute "
                "{attribute_name!r}".format(
                    class_name=self.__class__.__name__,
                    attribute_name='bar')
                , )
            raise e

    @bar.setter
    def bar(self, x):
        self.x = 3 * x

In [10]:
hoo = Hoo()
hoo


Out[10]:
<__main__.Hoo at 0xb419a80c>

In [11]:
hoo.bar


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-7270472a9752> in <module>()
----> 1 hoo.bar

<ipython-input-9-34504e9ddaf1> in bar(self)
     17                     attribute_name='bar')
     18                 , )
---> 19             raise e
     20 
     21     @bar.setter

<ipython-input-9-34504e9ddaf1> in bar(self)
      3     def bar(self):
      4         try:
----> 5             return self.x
      6         except AttributeError as e:
      7             # print('old e.args', repr(e.args))

AttributeError: 'Hoo' object has no attribute 'bar'