Does python have an elegant way to handle this?
To avoid exceptions when printing unrelated names, the most elegant way is not to print them; the second most elegant is to ensure that the names are associated, for example. linking them at the beginning of the function (for this purpose, placeholder None used along the way).
If not, what about the inelegant path?
try: print 'b is', b except NameError: print 'b is not bound'
In a complex function, I would prefer to avoid checking the existence of every local variable before I, for example, debugging information about them
It is also strongly recommended that maintaining your functions is simple (that is, not difficult). As Hoar wrote 30 years ago (in his Turing lecture, βImperial Clothing,β reprinted, for example, in this PDF ):
There are two ways to build software design: one way to do it is so simple that there are obviously no flaws, and to make it so complex that there are no obvious flaws. The first method is much more complicated.
Achieving and maintaining simplicity is really difficult: considering that you need to implement a certain general functionality of X, this is the most natural temptation in the world to do this through complex accretion into several complex classes and functions from different bits and parts, βsmartβ hacks, βcopy and insert "and" edit-bit "" disk encoding "etc. etc.
However, itβs worth trying instead to keep your functions βso simple that there are obviously no flaws.β If a function is complex for fully unit testing, it is too complex: break it (i.e., reorganize) into its natural components, even if it works to dig them out. (In fact, one of the ways in which to focus on unit testing helps to improve the quality of the code: relentlessly stimulating you so that all the code is fully tested, while at the same time encouraging you to make it simple in its structure).