[PATCH] A compromise on case

Martin von Loewis loewis at informatik.hu-berlin.de
Wed May 24 08:11:41 EDT 2000


nickm at mit.edu (Nick Mathewson) writes:

> Thanks!  I'm going to hold off on this for a few more iterations;
> the patch I wrote is not very clean or well-tested, and it
> definitely doesn't belong in the main dist.

Why not? It is helpful to all users, beginners or not. The only
disadvantage is the slow-down that it causes. That also is not a
problem if the exception results in program termination, since the
execution time of formatting a traceback is not relevant. It only
matters in cases where the caller expects to receive a NameError, in
which case the computation of the alternative name is wasted time.

> I mainly intended it as a demonstration of how I think errors should
> work.  If people agree with me, then I'll clean up the code.

I have two suggestions: In order to avoid hard-coding the error
message, I recommend to put this code into NameError and
AttributeError, like this:

class NameError(StandardError):
  def __str__(self):
    if len(self.args)==2:
      return "unknown name %s, do you mean %s ?" % self.args
    else:
      return StandardError.__str__(self)

Then, you create a name error with NameError(not_found, do_you_mean)

Next, if you want to delay computation of the alternative name, you
could also define

class AttributeError(StandardError):
  def __str__(self):
    if len(self.args)==2:
      name = self.args[0]
      obj = self.args[1]
      otype = type(obj)
      if otype in [InstanceType, ClassType, ModuleType]:
        dict = obj.__dict__
        rname = find_nearest_match(dict,name)
        if rname:
          return "%s object has no attribute %s, maybe you meant %s"\
                  % (otype.__name__, name, rname)
        return "%s object has no attribute %s" % (otype.__name__,name)
    return StandardError.__str__(self)

Then, an attribute error would be raised as AttributeError(name,obj).
That holds a reference to the object, but that should be ok, since it
does not introduce a cyclic reference.

Given an intelligent implemenentation of find_nearest_match, it could
also detect other kinds of typos.

I'd love to see such a feature in standard Python.

Regards,
Martin



More information about the Python-list mailing list