Wandering Thoughts archives

2007-03-31

Created functions and exception stack backtraces

There's a problem with functions that make functions: they obscure information in exception stack backtraces, because all of the created functions have the same name. If you have a lot of auto-created functions, just which one is blowing up and how do you tell them apart?

(I noted a similar effect with lambdas back here.)

A function's name is part of its func_code attribute, specifically func_code.co_name. Unfortunately this attribute is read-only, so you can't have your function creating function rewrite the name of a created function to something more useful for stack backtraces. (While you can change the function's __name__ attribute, it is not used for stack backtraces.)

A similar effect happens with functions that create classes (don't look at me like that; sometimes it can look like the right thing to do). Fortunately, you can rename classes by writing to their __name__ attribute and thus make it so that objects of each different created class have a a distinct repr() and so on, which is quite useful for debugging the resulting potential mess.

(I think changing __name__ is somewhat less work than writing a custom __repr__ function in the generic class framework, and besides you'd have to save the naming information somewhere anyways.)

CreatedFunctionsProblem written at 18:17:58; Add Comment


Page tools: See As Normal.
Search:
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.