How to pop the interpreter's stack?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Dec 15 05:16:14 EST 2010
On Tue, 14 Dec 2010 21:14:35 +0000, kj wrote:
> Consider this code:
>
>
> def spam(*args, **kwargs):
> args, kwargs = __pre_spam(*args, **kwargs)
>
> # args & kwargs are OK: proceed
> # ...
>
>
> def __pre_spam(*args, **kwargs):
> # validate args & kwargs;
> # return canonicalized versions of args & kwargs; # on failure,
> raise some *informative* exception # ...
> return canonicalized_args, canonicalized_kwargs
Double leading underscores don't have any special meaning in the global
scope. Save yourself an underscore and call it _pre_spam instead :)
In fact, even if spam and __pre_spam are methods, it's probably a good
idea to avoid the double-underscore name mangling. It's usually more
trouble than it's worth.
> I write functions like __pre_spam for one reason only: to remove clutter
> from a corresponding spam function that has a particularly complex
> argument-validation/canonicalization stage. In effect, spam
> "outsources" to __pre_spam the messy business of checking and
> conditioning its arguments.
A perfectly sensible arrangement.
> The one thing I don't like about this strategy is that the tracebacks of
> exceptions raised during the execution of __pre_spam include one
> unwanted stack level (namely, the one corresponding to __pre_spam
> itself).
But why is it unwanted? The traceback shows where the error occurs -- it
occurs in __pre_spam, not spam, or __post_spam, or spam_caller, or
anywhere else. Even if it's possible, having the traceback *lie* about
where it occurs is a bad idea which will cause confusion to anyone trying
to maintain the software in the future.
I can't think of any way to do it, but frankly I haven't thought too hard
about it. I'm glad I can't think of any way of doing it, because the
thought of having tracebacks lie about where they come from gives me the
shivers. Imagine debugging when you've edited the source but are still
running the old version, and now the reported line numbers don't match up
with the source file -- it would be like that, only worse.
--
Steven
More information about the Python-list
mailing list