An object which has no attributes but produces a more informative error message when accessed. Parameters ---------- name : str The name of the object. This will appear in the error messages. Notes ----- One common use for this object is so ensure that an attrib
| 1 | class NamedExplodingObject(object): |
| 2 | """An object which has no attributes but produces a more informative |
| 3 | error message when accessed. |
| 4 | |
| 5 | Parameters |
| 6 | ---------- |
| 7 | name : str |
| 8 | The name of the object. This will appear in the error messages. |
| 9 | |
| 10 | Notes |
| 11 | ----- |
| 12 | One common use for this object is so ensure that an attribute always exists |
| 13 | even if sometimes it should not be used. |
| 14 | """ |
| 15 | def __init__(self, name, extra_message=None): |
| 16 | self._name = name |
| 17 | self._extra_message = extra_message |
| 18 | |
| 19 | def __getattr__(self, attr): |
| 20 | extra_message = self._extra_message |
| 21 | raise AttributeError( |
| 22 | 'attempted to access attribute %r of ExplodingObject %r%s' % ( |
| 23 | attr, |
| 24 | self._name, |
| 25 | ), |
| 26 | ' ' + extra_message if extra_message is not None else '', |
| 27 | ) |
| 28 | |
| 29 | def __repr__(self): |
| 30 | return '%s(%r%s)' % ( |
| 31 | type(self).__name__, |
| 32 | self._name, |
| 33 | # show that there is an extra message but truncate it to be |
| 34 | # more readable when debugging |
| 35 | ', extra_message=...' if self._extra_message is not None else '', |
| 36 | ) |
no outgoing calls