[PATCH] A compromise on case
Martin von Loewis
loewis at informatik.hu-berlin.de
Wed May 24 14:11:41 CEST 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:
return "unknown name %s, do you mean %s ?" % self.args
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
name = self.args
obj = self.args
otype = type(obj)
if otype in [InstanceType, ClassType, ModuleType]:
dict = obj.__dict__
rname = find_nearest_match(dict,name)
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)
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.
More information about the Python-list