tcl:包装同名的过程
我想用同名和调用约定的过程替换“proc N”的定义,但需要一些额外的错误检测代码。
在 python 中,我可以像下面那样做我想做的事情,但我对命名空间和函数句柄在 tcl 中如何工作没有任何了解。
__orig_N = N
def N(arg1, arg2):
if arg1 != 'GOOD VALUE':
exit('arg1 is bad')
return __orig_N(arg1, arg2)
I want to replace the definition of "proc N" with a proc of the same name and calling conventions, but with a little extra error detection code.
In python I could do what I want like below, but I don't have any grasp of how namespaces and function handles work in tcl.
__orig_N = N
def N(arg1, arg2):
if arg1 != 'GOOD VALUE':
exit('arg1 is bad')
return __orig_N(arg1, arg2)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
rename
命令重命名现有的过程:这实际上比Python原始版本更复杂一些,因为
uplevel
的使用有效地消除了包装器整个调用堆栈——诚然,这在您的情况下可能不是必需的,但能够做到这一点很好。You can use the
rename
command to rename an existing proc:This is actually a little bit more sophisticated than the python original, in that the use of
uplevel
effectively elides the wrapper from the call stack entirely -- which may not be necessary in your case, admittedly, but it's nice to be able to do it.Tcl对程序有很好的自省。这允许您重写一个过程以添加更多代码:
好的,这不是唯一的方法 - Eric 的答案更接近我通常包装命令的方式,并且它具有使用非过程命令的优点同样,但此解决方案的优点是可以很好且紧密地绑定代码,这样以后就很少会出错。它还不会在任何错误跟踪中引入额外的堆栈帧,这有助于保持调试简单。
Tcl's got quite good introspection on procedures. This lets you rewrite a procedure to add in some more code:
OK, that's not the only way to do it – Eric's answer is closer to how I'd normally wrap a command, and it has the advantage of working with non-procedure commands as well – but this solution has the advantage of binding the code in nice and tight so that there's very little to go wrong later. It also doesn't introduce extra stack frames into any error traces, which helps keep debugging simple.