mailRe: r2533 - in /1.2: errors.py prompt/interpreter.py relax


Others Months | Index by Date | Thread Index
>>   [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Header


Content

Posted by Chris MacRaild on August 11, 2006 - 11:27:
On Fri, 2006-08-11 at 16:39 +1000, Edward d'Auvergne wrote:
On 8/10/06, Chris MacRaild wrote:
On Thu, 2006-08-10 at 20:51 +1000, Edward d'Auvergne wrote:
Thanks.  I have a suggestion to simplify the state saving code and
that is that the save_state function is called within the BaseError
class.  This means that save_state is only called from one place in
the code by placing it within the __str__ function (which is called to
get the error message).  For example something like:

    class BaseError(Exception):
        def __str__(self):
            # Save the program state.
            if Debug:
                self.save_state()

            # The RelaxError message.
            return ("RelaxError: " + self.text + "\n")

There are a couple of reasons I didn't do it this way. One is that
__str__ is a 'special' function as far as Python is concerned, and it
exists for a specific purpose (same with all the double-underscore
functions). Although it's difficult to imagine how it might cause
problems in this case, I'm inclined to avoid messing with it on
principle.

Too late, I've already destroyed it ;)  I replaced it so that it
returns the specific RelaxError message generated and stored in
'self.text'.  I think the only problem with this special '__str__()'
function is that if it generates an error, you're in big trouble.

You havn't destroyed it. The special purpose of self.__str__() is to
return a string representation of self (ie. the current instance of the
class). This is exactly what __str__() does, as it stands. You have
overridden the __str__() inherited from the parent class (Exception) to
give a more meaningful string representation of the various RelaxErrors.
This is exactly the intended use of this special function. The mistake
would be to add additional behaviour to this function which is not
related to the string representation. To give an example of how it might
cause confusion, imagine a case where we wanted to downgrade a
particular RelaxError to a RelaxWarning at run time. To do this, we
might insert the following:

try:
    do_something_bugy()
except RelaxError:
    err = sys.exc_info()
    msg = err[1].__str__()
    warn(RelaxWarning(msg))
finally:
    del err

This gets the exception instance from sys.exc_info, and explicitly gets
the string representation to use it as a warning message, so we get the
relevant message, even though we havn't raised the exception. Of course
we dont expect this code to cause a state.save(), as it would if that
code was included in __str__()

Chris





Related Messages


Powered by MHonArc, Updated Fri Aug 11 15:40:37 2006