[Python-ideas] Arguments to exceptions

Peter Otten __peter__ at web.de
Wed Jul 5 05:03:32 EDT 2017


Terry Reedy wrote:
> Alternate proposal: give the NameError class a .name instance method
> that extracts the name from the message.  This should not increase the
> time to create an instance.  You would then write 'err.name()' instead
> of 'err.name'. For 3.6
> 
> def name(self):
>      msg = self.args[0]
>      return msg[6:msg.rindex("'")]
> 
> # current test
> 
> try: xyz
> except NameError as e:
>      print(name(e) == 'xyz')
> 
> # Exceptions unittest to ensure that the method
> # stays synchronized with future versions of instances
> 
> def test_nameerror_name(self):
>      try:
>          xyz
>      except NameError as e:
>          self.assertEqual(e.name(), 'xyz')
> 
> Generalize to other exceptions.

This sounds a bit like "Nine out of ten guests in our restaurant want 
scrambled eggs -- let's scramble all eggs then as we can always unscramble 
on demand..."

Regardless of usage frequency it feels wrong to regenerate the raw data from 
the string representation, even when it's possible.

On the other hand, if AttributeError were implemented as

class AttributeError:
    def __init__(self, obj, name):
        self.obj = obj
        self.name = name

    @property
    def message(self):
        ... # generate message

constructing the error message could often be avoided.

It would also encourage DRY and put an end to subtle variations in the error 
message like

>>> NAME = "A" * 50 + "NobodyExpectsTheSpanishInquisition"
>>> exec("class {}: __slots__ = ()".format(NAME))
>>> A = globals()[NAME]
>>> A().foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' object 
has no attribute 'foo'
>>> A().foo = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANobodyExpectsTheSpanishInquisition' 
object has no attribute 'foo'




More information about the Python-ideas mailing list