ActiveState Code

Recipe 65429: Obtaining the name of a procedure


How to obtain the name of a procedure from within it.

Tcl
1
2
3
4
5
proc myProc {args} {
    set procName [lindex [info level 0] 0]
    puts "You called \"$procName\""
    puts "The full call was \"[info level 0]\""
}

Discussion

[info level n] returns information about a specific level in the callstack of procedures, namely the name of the command in that level and its arguments. This information is in a list and the name of the command is the first element. Level 0 refers to the currently executing procedure.

Comments

  1. 1. At 1:59 a.m. on 12 sep 2001, Richard Suchenwirth said:

    Some fixes. The proc as shown would constantly return "myProc", as it is asked for its name. Also, "puts" should be left to the caller. I propose to rewrite it as

    proc myName {} {lindex [info level 1] 0}
    

    A practical application is in an overloaded widget procedure.

  2. 2. At 1:30 p.m. on 25 apr 2002, David Snyderman said:

    Is this more useful? Would the following name return proc be of more use?

    proc myname {} {
    
        set level [expr [info leve] - 1]
    
        return [lindex [info level $level] 0]
    
    }
    
    
    
    Perhaps accompanied by:
    
    
    
    proc calledby {} {
    
        set level [expr [info leve] - 2]
    
        if { $level > 0 } {
    
            return [lindex [info level $level ] 0]
    
        } else {
    
            if { [string length [info script] ] > 0 } {
    
                return [info script]
    
            } else {
    
                return [info nameofexecutable]
    
            }
    
        }
    
    }
    

Sign in to comment