Tcl: wrap prok with the same name

I want to replace the definition of "proc N" with proc with the same name and calls, but with a little extra error detection code.

In python, I could do what I want, as shown below, but I don't understand how namespaces and function descriptors work in tcl.

__orig_N = N def N(arg1, arg2): if arg1 != 'GOOD VALUE': exit('arg1 is bad') return __orig_N(arg1, arg2) 
+4
source share
2 answers

Tcl received a good introspection of the procedures. This allows you to rewrite the procedure to add to some code:

 # 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]] 

OK, this is not the only way to do this - Eric's answer is closer to how I usually wrap a team, and it has the advantage of working with teams without procedures, but this advantage has the advantage of binding the code in a good and tight state, so that in later it was a bit wrong. It also does not introduce extra stack frames into any traces of errors, which simplifies debugging.

+4
source

You can use the rename command to rename an existing proc:

 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] } 

This is actually a bit more complicated than the original python, since using uplevel effectively completely eliminates the shell from the call stack, which may not be necessary in your case, but it is nice to be able to do this.

+10
source

All Articles