Search code examples
tcl

Calling a procedure with or without a namespace inside another procedure


I have this procedure:

proc myNS::main {args} {
    # Inside this procedure I can call another 
    # procedure with same namespace like this :
    procedure2
    # Or full namespace
    myNS::procedure2
}

I often see the 2 writings (I measured the time of my proc myNS::main with procedure2 or myNS::procedure2, it's the same time).
Is it a question of style, or is it better to use one or the other ?


Solution

  • Summary: use any form that works and which is meaningful for you, unless you have a good reason not to.


    When you use a command name that is not fully qualified (i.e., starting with ::) that command name is resolved with respect to the current resolution context. The current resolution context is typically based on looking in the current namespace, then the namespaces on the current namespace's path (see namespace path), and then finally the global namespace. (It doesn't need to be, but most code doesn't install alternate resolution engines.)

    The current namespace for a procedure is whatever procedure contains that procedure. This is only true for procedures. You can use namespace eval and apply to select a different namespace explicitly; the tailcall command can also interact with resolution, as it resolves in the current context before discarding it. If you use TclOO, that does more complex things with namespaces and methods; mostly there, you should think of the current namespace as being for the current object instance.

    By convention, if a documented Tcl command has no :: in its documented name, that command is in the global namespace, but should typically be used as an unqualified name. That's not true everywhere, but using the documented name should work (unless you're doing something tricky like creating commands in your current namespace called set, if, open, etc.)

    Command resolutions are usually cached aggressively (where the command is not directly changed into bytecode): the caching mechanisms know when to invalidate so you can ignore it. Write what you want, and only worry about speed if you think there's a problem.