tcl:包装一个同名的proc



我想用相同名称和调用约定的proc替换"proc N"的定义,但添加一些额外的错误检测代码。

在python中,我可以像下面这样做,但我不知道名称空间和函数处理在tcl中是如何工作的。

__orig_N = N
def N(arg1, arg2):
    if arg1 != 'GOOD VALUE':
        exit('arg1 is bad')
    return __orig_N(arg1, arg2)

您可以使用rename命令重命名现有进程:

rename N __orig_N
proc N {arg1 arg2} {
    if { $arg1 != "GOOD_VALUE" } {
        puts stderr "arg1 is bad"
        exit 1
    }
    return [uplevel 1 __orig_N $arg1 $arg2]
}

这实际上比python的原始版本复杂一点,因为uplevel的使用有效地从调用堆栈中完全消除了包装器——诚然,这在您的情况下可能没有必要,但能够做到这一点很好

Tcl对过程进行了很好的内省。这可以让你重写一个过程来添加更多的代码:

# Assume there are no defaults; defaults make this more complicated...
proc N [info args N] [concat {
    # Use 'ne' for string comparison, '!=' for numeric comparison
    if {$arg1 ne "GOOD VALUE"} {
        error "arg1 is bad"
        # The semicolon is _important_ because of the odd semantics of [concat]
    };
} [info body N]]

好吧,这不是唯一的方法——Eric的答案更接近于我通常对命令的包装方式,它也有处理非过程命令的优势——但这个解决方案的优势是将代码绑定得又好又紧,这样以后就不会出错。它也不会在任何错误跟踪中引入额外的堆栈帧,这有助于保持调试的简单性。

最新更新