Does python have an elegant way to handle this?
为了避免打印绑定名称例外以外的变量,最优雅的方式是不打印;第二个最优雅的是确保名称确实受到约束,例如,通过绑定他们在功能的开始(占位符None
是流行为此目的)。
If not, what about an inelegant way?
try: print 'b is', b
except NameError: print 'b is not bound'
In a complicated function I'd prefer to avoid testing the existence of every local variable before I, for example, printed debug information about them
保持你的函数的简单(即不复杂)强烈推荐的。由于霍尔写道:30年前(在他的图灵验收演讲“皇帝的旧衣服”,转载例如,在this PDF):
There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.
实现和维护简单是确实很难:因为你必须实现一定的总功能X,世界上最诱人的诱惑是通过复杂的增加,进入一些复杂的类和各种各样的功能,“巧妙”的黑客,复制和粘贴和编辑一集“驱动式编码”等等。
然而,努力工作,而不是让功能“如此简单以至于有o显然没有缺陷“。如果一个函数很难完全进行单元测试,那么它太复杂了:将它分解(即重构它)到它的自然组件中,即使它需要发掘它们。 (这实际上是强调单元测试有助于代码质量的方法之一:通过激励你不懈地保持所有代码的完美测试,同时促使你在的结构中简化)。
办理什么定义?假设在“except”条款中打印什么? – SilentGhost 2010-04-30 13:52:12