namespace(3tcl)

πŸ’– namespace β€” Tcl Built-In Commands πŸ’–

okay bestie, buckle UP, we're doing namespace(3tcl) today and honestly? it's giving main character energy fr fr ✨


🌸 NAME 🌸

namespace β€” the way to create and manipulate contexts for commands and variables. no cap, it's the whole vibe.


πŸŽ€ SYNOPSIS πŸŽ€

namespace subcommand ?arg ...?

πŸ’… DESCRIPTION πŸ’…

bestie. listen. the namespace command is literally the blueprint for keeping your commands and variables in their own little corners (contexts) so they don't all pile into one giant messy group chat. you can create, access, and destroy these separate contexts, and honestly? iconic behavior.

if you want the full lore on what a namespace even is, slide down to the WHAT IS A NAMESPACE? section below πŸ’–

the legal values of subcommand are listed right here. and yes, you can abbreviate the subcommands β€” she's flexible like that πŸ’…


πŸ¦‹ namespace children ?namespace? ?pattern?

returns a list of all the child namespaces that belong to the namespace namespace. if you don't specify namespace, then she just hands you the children of the current namespace. cute.

this command returns fully-qualified names, which start with a double colon (::). if you throw in the optional pattern, she only returns the names matching that glob-style pattern. the actual pattern used is figured out like this: if a pattern starts with a double colon (::), it's used directly β€” otherwise the namespace namespace (or the fully-qualified name of the current namespace) gets prepended onto the pattern. slay 🌈

πŸ¦‹ namespace code script

captures the current namespace context for later execution of the script script. it returns a fresh new script where script has been wrapped in a namespace inscope command. the new script is a whole mood with two important properties:

  • First β€” it can be evaluated in any namespace and will cause script to be evaluated in the current namespace (the one where the namespace code command was invoked). she's loyal like that πŸ’œ
  • Second β€” additional arguments can be appended to the resulting script, and they'll get passed to script as additional arguments.

for example, suppose the command set script [namespace code {foo bar}] is invoked in namespace ::a::b. then eval $script [list x y] can be executed in any namespace (assuming the value of script has been passed in properly) and will have the same effect as the command ::namespace eval ::a::b {foo bar x y}.

this command exists because extensions like Tk normally execute callback scripts in the global namespace. a scoped command captures a command together with its namespace context in a way that lets it be executed properly later. see the SCOPED SCRIPTS section for some examples of how this is used to create callback scripts ✨

πŸ¦‹ namespace current

returns the fully-qualified name for the current namespace. here's the tea though: the actual name of the global namespace is β€œβ€ (i.e., an empty string), but this command returns :: for the global namespace as a lil convenience to programmers. so thoughtful πŸ₯Ί

πŸ¦‹ namespace delete ?namespace namespace ...?

every namespace namespace is deleted, and all variables, procedures, and child namespaces chillin' inside get deleted too πŸ’€. if a procedure is currently executing inside the namespace, the namespace will be kept alive until that procedure returns β€” BUT (big but) the namespace gets marked so other code can't look it up by name anymore. she's ghosted, not gone.

if a namespace doesn't exist, this command returns an error. and if you give no namespace names at all? this command does literally nothing. rest well queen πŸ™ˆ

πŸ¦‹ namespace ensemble subcommand ?arg ...?

creates and manipulates a command that's formed out of an ensemble of subcommands. see the ENSEMBLES section below for further details.

πŸ¦‹ namespace eval namespace arg ?arg ...?

activates a namespace called namespace and evaluates some code in that context. if the namespace doesn't already exist, it gets created. if you pass more than one arg argument, the arguments get concatenated together with a space between each one, in the same fashion as the eval command, and the result gets evaluated.

if namespace has leading namespace qualifiers and any of those leading namespaces don't exist, they are automatically created. no prep work required bestie πŸ’…

πŸ¦‹ namespace exists namespace

returns 1 if namespace is a valid namespace in the current context, returns 0 otherwise. simple. clean. a yes or no girlie. ✨

πŸ¦‹ namespace export ?-clear? ?pattern pattern ...?

specifies which commands are exported from a namespace. the exported commands are those that can later be imported into another namespace using a namespace import command. both commands defined in a namespace and commands the namespace has previously imported can be exported by a namespace. the commands don't even have to be defined at the time the namespace export command is executed β€” living in the future, we love that for her πŸ¦‹

each pattern may contain glob-style special characters, but it may not include any namespace qualifiers β€” meaning the pattern can only specify commands in the current (exporting) namespace. each pattern gets appended onto the namespace's list of export patterns.

  • if the -clear flag is given, the namespace's export pattern list is reset to empty before any pattern arguments are appended.
  • if no patterns are given and the -clear flag is not given, this command returns the namespace's current export list. πŸŽ€

πŸ¦‹ namespace forget ?pattern pattern ...?

removes previously imported commands from a namespace. each pattern is a simple or qualified name such as x, foo::x, or a::b::p*. qualified names contain double colons (::) and qualify a name with the name of one or more namespaces. ngl, the details matter here bestie:

  • each β€œqualified pattern” is qualified with the name of an exporting namespace and may have glob-style special characters in the command name at the end of the qualified name. glob characters may not appear in a namespace name.
  • for each β€œsimple pattern”, this command deletes the matching commands of the current namespace that were imported from a different namespace.
  • for β€œqualified patterns”, this command first finds the matching exported commands. it then checks whether any of those commands were previously imported by the current namespace. if so, this command deletes the corresponding imported commands.

in effect, this undoes the action of a namespace import command. it's the ctrl+z of imports, fr fr πŸ”₯

πŸ¦‹ namespace import ?-force? ?pattern pattern ...?

imports commands into a namespace, or queries the set of imported commands in a namespace. when no arguments are present, namespace import returns the list of commands in the current namespace that have been imported from other namespaces. the commands in the returned list are in the format of simple names, with no namespace qualifiers at all. this format is suitable for composition with namespace forget (see EXAMPLES below).

when pattern arguments are present, each pattern is a qualified name like foo::x or a::p*. that is, it includes the name of an exporting namespace and may have glob-style special characters in the command name at the end of the qualified name. glob characters may not appear in a namespace name. when the namespace name isn't fully qualified (i.e., doesn't start with a namespace separator), it gets resolved as a namespace name in the way described in the NAME RESOLUTION section; it is an error if no namespace with that name can be found. ⚠️

all the commands that match a pattern string and which are currently exported from their namespace get added to the current namespace. this is done by creating a new command in the current namespace that points to the exported command in its original namespace; when the new imported command is called, it invokes the exported command. ✨

this command normally returns an error if an imported command conflicts with an existing command. however, if the -force option is given, imported commands will silently replace existing commands. be careful with that one bestie, she's spicy 🌢️

the namespace import command has snapshot semantics: that is, only requested commands that are currently defined in the exporting namespace are imported. in other words, you can import only the commands that are in a namespace at the time when the namespace import command is executed. if another command is defined and exported in this namespace later on, it will not be imported. periodt. πŸ’…

πŸ¦‹ namespace inscope namespace script ?arg ...?

executes a script in the context of the specified namespace. this command isn't really expected to be used directly by programmers; calls to it are generated implicitly when applications use namespace code commands to create callback scripts that the applications then register with, e.g., Tk widgets. iykyk 🫢

the namespace inscope command is a lot like the namespace eval command, except that the namespace must already exist, and namespace inscope appends additional *arg*s as proper list elements.

namespace inscope ::foo $script $x $y $z

is equivalent to

namespace eval ::foo [concat $script [list $x $y $z]]

thus additional arguments will not undergo a second round of substitution, as is the case with namespace eval. no double-dipping allowed πŸ’€

πŸ¦‹ namespace origin command

returns the fully-qualified name of the original command to which the imported command command refers. when a command is imported into a namespace, a new command is created in that namespace that points to the actual command in the exporting namespace.

if a command is imported into a sequence of namespaces a, b,...,n where each successive namespace just imports the command from the previous namespace, this command returns the fully-qualified name of the original command in the first namespace, a. if command doesn't refer to an imported command, the command's own fully-qualified name is returned. it's like finding the source of a rumor, bestie πŸ•΅οΈβ€β™€οΈπŸ’–

πŸ¦‹ namespace parent ?namespace?

returns the fully-qualified name of the parent namespace for namespace namespace. if namespace is not specified, the fully-qualified name of the current namespace's parent is returned. found family energy, honestly πŸ₯ΊπŸ‘‘


mooore coming bestie, don't go anywhere πŸ’œ

  • namespace path ?namespaceList? β€” returns the command resolution path of the current namespace. If you pass namespaceList as a list of named namespaces, then boom πŸ’₯ the current namespace's command resolution path gets set to those namespaces, and the command returns the empty list. And bestie, the default command resolution path is always empty. The rules for how any of this resolves live down in NAME RESOLUTION below πŸ‘‡
  • namespace qualifiers string β€” hands you back any leading namespace qualifiers for string. Qualifiers are namespace names separated by double colons (::). So for the string ::foo::bar::x this gives you ::foo::bar, and for :: it gives you an empty string. This one is the complement of the namespace tail command 🫢. Heads up though: it does not check whether the namespace names are, like, actually the names of currently defined namespaces. It's not doing a vibe check on reality, it's just chopping the string βœ‚οΈ
  • namespace tail string β€” returns the simple name sitting at the end of a qualified string. Qualifiers are namespace names separated by double colons (::). For the string ::foo::bar::x, this returns x, and for :: it returns an empty string. It's the complement of the namespace qualifiers command. And same disclaimer as above: it does not check whether those namespace names are the names of currently defined namespaces. Purely string surgery, no cap πŸ’…
  • namespace upvar namespace ?otherVar myVar ...? β€” this one arranges for zero or more local variables in the current procedure to refer to variables in namespace. The namespace name gets resolved as described in NAME RESOLUTION. And okay, listen, namespace upvar $ns a b has the exact same behaviour as upvar 0 ${ns}::a b, with the sole exception of the resolution rules used for qualified namespace or variable names. Also it returns an empty string, because of course it does πŸ™ˆ
  • namespace unknown ?script? β€” sets or returns the unknown command handler for the current namespace. That handler gets invoked whenever a command called from inside the namespace can't be found in the current namespace, nor in the namespace's path, nor in the global namespace πŸ‘». The script argument, if you give one, should be a well formed list representing a command name and optional arguments. When the handler fires, the full invocation line gets appended to the script and the result gets evaluated in the context of the namespace. The default handler for all namespaces is ::unknown. If you pass no argument at all, it just returns the handler for the current namespace ✨
  • namespace which ?-command? ?-variable? name β€” looks up name as either a command or a variable and returns its fully-qualified name πŸŽ€. For example, if name doesn't exist in the current namespace but does exist in the global namespace, this command returns a fully-qualified name in the global namespace. If the command or variable doesn't exist, you get an empty string back πŸ’€. If the variable has been created but not defined β€” like with the variable command, or through a trace on the variable β€” this command will still return the fully-qualified name of the variable πŸ‘‘. If no flag is given, name is treated as a command name. See NAME RESOLUTION below for the name resolution rules 🌈

🌸 WHAT IS A NAMESPACE? 🌸

A namespace is a lil collection of commands and variables πŸ’–. It encapsulates the commands and variables so they will not interfere with the commands and variables of other namespaces. Tcl has always had one such collection, which we call the global namespace. The global namespace holds all global variables and commands. And the namespace eval command lets you create new namespaces ✨

For example:

namespace eval Counter {
    namespace export bump
    variable num 0

    proc bump {} {
        variable num
        incr num
    }
}

creates a new namespace containing the variable num and the procedure bump. The commands and variables in this namespace are separate from other commands and variables in the same program πŸ¦‹. If there's a command named bump in the global namespace, for example, it will be different from the command bump in the Counter namespace. Two different girlies, same name, zero drama πŸ’…

Namespace variables resemble global variables in Tcl. They exist outside of the procedures in a namespace but can be accessed in a procedure via the variable command, as shown in the example above πŸ‘†

Namespaces are dynamic. You can add and delete commands and variables at any time, so you can build up the contents of a namespace over time using a series of namespace eval commands πŸ”₯. For example, the following series of commands has the same effect as the namespace definition shown above:

namespace eval Counter {
    variable num 0
    proc bump {} {
        variable num
        return [incr num]
    }
}
namespace eval Counter {
    proc test {args} {
        return $args
    }
}
namespace eval Counter {
     rename test ""
}

Note that the test procedure gets added to the Counter namespace, and later removed via the rename command πŸ”ͺ

Namespaces can have other namespaces within them, so they nest hierarchically πŸͺ†. A nested namespace is encapsulated inside its parent namespace and can not interfere with other namespaces. It's giving Russian nesting dolls, honestly.


✨ QUALIFIED NAMES ✨

Each namespace has a textual name such as history or ::safe::interp πŸ‘‘. Since namespaces may nest, qualified names are used to refer to commands, variables, and child namespaces contained inside namespaces. Qualified names are similar to the hierarchical path names for Unix files or Tk widgets, except that :: is used as the separator instead of / or . πŸ“

The topmost or global namespace has the name "" (i.e., an empty string), although :: is a synonym 🫢. As an example, the name ::safe::interp::create refers to the command create in the namespace interp that is a child of namespace ::safe, which in turn is a child of the global namespace, :: 🌈

If you want to access commands and variables from another namespace, you must use some extra syntax πŸ’«. Names must be qualified by the namespace that contains them. From the global namespace, we might access the Counter procedures like this:

Counter::bump 5
Counter::Reset

We could access the current count like this:

puts "count = $Counter::num"

When one namespace contains another, you may need more than one qualifier to reach its elements 🧚. If we had a namespace Foo that contained the namespace Counter, you could invoke its bump procedure from the global namespace like this:

Foo::Counter::bump 3

You can also use qualified names when you create and rename commands πŸ’…. For example, you could add a procedure to the Foo namespace like this:

proc Foo::Test {args} {return $args}

And you could move the same procedure to another namespace like this:

rename Foo::Test Bar::Test

There are a few remaining points about qualified names that we should cover πŸ“. Namespaces have nonempty names except for the global namespace. :: is disallowed in simple command, variable, and namespace names except as a namespace separator. Extra colons in any separator part of a qualified name are ignored; i.e. two or more colons are treated as a namespace separator. A trailing :: in a qualified variable or command name refers to the variable or command named {}. However, a trailing :: in a qualified namespace name is ignored πŸ™ˆ


🌈 NAME RESOLUTION 🌈

okay bestie, so here's the tea β˜• β€” pretty much every Tcl command that takes a variable name or a command name out here supports qualified names. Like, set, proc, rename, interp alias… all of them. If you hand over a fully-qualified name that starts with ::, there is literally zero question about which command, variable, or namespace you mean. Iconic. But if the name does not start with a :: (aka it's relative, we love a lowkey name), Tcl follows some basic rules to look it up:

  • Variable names β€” always resolved starting in the current namespace. In the absence of special resolvers, foo::bar::baz refers to a variable named "baz" in a namespace named "bar" that is a child of a namespace named "foo" that is a child of the current namespace of the interpreter. Nested girlies, fr fr.
  • Command names β€” always resolved by looking in the current namespace first. If it's not found there, they get searched for in every namespace on the current namespace's command path (which is empty by default, yes, absolutely empty, no cap). If it's still not found, command names are looked up in the global namespace (or, failing that, they get processed by the appropriate namespace unknown handler 🫢).
  • Namespace names β€” always resolved by looking in only the current namespace. That's it. That's the rule. Periodt.

So like, take this example:

set traceLevel 0
namespace eval Debug {
    printTrace $traceLevel
}

Tcl looks for traceLevel in the namespace Debug. And it looks up the command printTrace in the same way. If a variable or command name isn't found, then bestie… the name is undefined 😭. To make this point absolutely clear, consider this one:

set traceLevel 0
namespace eval Foo {
    variable traceLevel 3

    namespace eval Debug {
        printTrace $traceLevel
    }
}

Here Tcl looks for traceLevel in the namespace Foo::Debug. The variables Foo::traceLevel and Foo::Debug::traceLevel are completely ignored during the name resolution process. Not even a vibe check. Ignored. πŸ’€

You can always use the namespace which command to clear up any question about name resolution. For example, the command:

namespace eval Foo::Debug {namespace which -variable traceLevel}

returns the empty string. And the command,

namespace eval Foo {namespace which -variable traceLevel}

returns the empty string as well. Yeah. Both empty. Crickets. πŸ¦—


As mentioned above (and it bears repeating, bestie), namespace names and variables are looked up differently than the names of commands. Namespace names and variables are always resolved in the current namespace. Which means, for example, that a namespace eval command that creates a new namespace always creates a child of the current namespace β€” unless the new namespace name begins with ::. iykyk.

Tcl has no access control to limit what variables, commands, or namespaces you can reference. Not a single gatekeeper, not one bouncer at the door πŸ™ˆ. If you provide a qualified name that resolves to an element by the name resolution rule above, you can access the element. That's it.

Also! You can access a namespace variable from a procedure in the same namespace by using the variable command. Much like the global command, this creates a local link to the namespace variable. And if necessary, it also creates the variable in the current namespace and initializes it. Note that the global command only creates links to variables in the global namespace. And it is not necessary to use a variable command if you always refer to the namespace variable using an appropriate qualified name. You do you, queen ✨.


πŸ“¦ IMPORTING COMMANDS πŸ“¦

Namespaces are often used to represent libraries. And some library commands are used so frequently that typing out their qualified names is genuinely a nuisance, like why 😭. For example, suppose that all of the commands in a package like BLT are contained in a namespace called Blt. Then you might access these commands like this:

Blt::graph .g -background red
Blt::table . .g 0,0

If you use the graph and table commands frequently, you may want to access them without the Blt:: prefix. And you can do this by importing the commands into the current namespace, like this:

namespace import Blt::*

This adds all exported commands from the Blt namespace into the current namespace context, so you can write code like this:

graph .g -background red
table . .g 0,0

The namespace import command only imports commands from a namespace that, well, that namespace exported with a namespace export command. No export, no import, no exceptions πŸ’….

okay real talk β€” importing every command from a namespace is generally a bad idea, since you do not know what you will get. It's better to import just the specific commands you need. Like, be intentional bestie.

For example, the command

namespace import Blt::graph Blt::table

imports only the graph and table commands into the current context. Just those two. Perfect, chef's kiss πŸ‘‘.

If you try to import a command that already exists, you will get an error. This prevents you from importing the same command from two different packages. Which is great until it isn't. But from time to time (perhaps when debugging πŸ‘€), you may want to get around this restriction. You may want to reissue the namespace import command to pick up new commands that have appeared in a namespace. In that case, you can use the -force option, and existing commands will be silently overwritten:

namespace import -force Blt::graph Blt::table

If for some reason you want to stop using the imported commands, you can remove them with a namespace forget command, like this:

namespace forget Blt::*

This searches the current namespace for any commands imported from Blt. If it finds any, it removes them. Otherwise, it does nothing. Literally nothing, it just vibes. After this, the Blt commands must be accessed with the Blt:: prefix again. Back to typing, unfortunately 🫠.

And when you delete a command from the exporting namespace like this:

rename Blt::graph ""

the command is automatically removed from all namespaces that import it. Clean. Tidy. Slay ✨.


πŸŽ€ EXPORTING COMMANDS πŸŽ€

You can export commands from a namespace like this:

namespace eval Counter {
    namespace export bump reset
    variable Num 0
    variable Max 100

    proc bump {{by 1}} {
        variable Num
        incr Num $by
        Check
        return $Num
    }
    proc reset {} {
        variable Num
        set Num 0
    }
    proc Check {} {
        variable Num
        variable Max
        if {$Num > $Max} {
            error "too high!"
        }
    }
}

The procedures bump and reset are exported, so they are included when you import from the Counter namespace, like this:

namespace import Counter::*

However, the Check procedure is not exported, so it is ignored by the import operation. Sorry Check, bestie, you're on your own πŸ™ˆ.

The namespace import command only imports commands that were declared as exported by their namespace. The namespace export command specifies what commands may be imported by other namespaces. And if a namespace import command specifies a command that is not exported, the command is simply not imported. That's the whole deal, no cap πŸ”₯.


🧚 SCOPED SCRIPTS 🧚

The namespace code command is the means by which a script may be packaged for evaluation in a namespace other than the one in which it was created. It is used most often to create event handlers, Tk bindings, and traces for evaluation in the global context. For instance, the following code indicates how to direct a variable trace callback into the current namespace:

namespace eval a {
    variable b
    proc theTraceCallback { n1 n2 op } {
        upvar 1 $n1 var
        puts "the value of $n1 has changed to $var"
        return
    }
    trace add variable b write [namespace code theTraceCallback]
}
set a::b c

When executed, it prints the message:

the value of a::b has changed to c

see, it travels with you. main character energy, honestly πŸ‘‘πŸ¦‹.

🫢 ENSEMBLES 🫢

Okay bestie, this is the part everyone actually shows up for. The namespace ensemble is how you build and mess with ensemble commands β€” and an ensemble command is just a command made by gluing a bunch of subcommands together into one ✨. The commands it groups usually come from the current namespace at the moment the ensemble got created, but like, that's configurable, we have options, we're flexible πŸ’….

Lowkey important: there can be any number of ensembles attached to any namespace β€” including zero, which is literally the default state of every namespace that has ever existed. But the second that namespace gets deleted, all the ensembles linked to it get deleted too, no survivors 😭. Meanwhile the link between an ensemble command and its namespace sticks around however you rename the ensemble. Rename it, move it, it still knows where home is 🏠.

Three subcommands of the namespace ensemble command are defined β€” here's the whole lineup:

  • namespace ensemble create ?option value ...? β€” makes a new ensemble command linked to the current namespace, and hands you back the fully qualified name of the command it just made πŸ‘‘. The arguments to namespace ensemble create let you configure the command exactly as if you'd used the namespace ensemble configure command. And unless you override it with the -command option, this command creates an ensemble with exactly the same name as the linked namespace. Full list of options and what they do? Scroll to ENSEMBLE OPTIONS below, it's all there.
  • namespace ensemble configure command ? option ? ? value ... ? β€” either fetches the value of an option attached to the ensemble command named command, or updates some options attached to that ensemble command. Again: ENSEMBLE OPTIONS below, full list, we're thorough here πŸ’–.
  • namespace ensemble exists command β€” returns a boolean describing whether the command command exists and is an ensemble command. And the only way this one ever errors is if you passed the wrong number of arguments. That's it. That's the only way. Fr fr πŸ™ˆ.

So when an ensemble command gets called, here's the tea: it takes its first argument and looks it up (using the rules described down below, bestie, stay with me) to discover a list of words that will replace the ensemble command and the subcommand. Then that resulting list of words gets evaluated β€” with no further substitutions β€” as if that's what you'd typed originally in the first place. (Like, by passing the list of words through Tcl_EvalObjv.) Then it returns the result of the command. And yes, it is fully legal to make the target of an ensemble rewrite be another ensemble command, or even the same ensemble command. We love a little recursion moment πŸŒ€.

One thing though: the ensemble command will not be visible through the use of the uplevel or info level commands. It's mysterious like that. Main character energy. πŸ’…

πŸ’œ ENSEMBLE OPTIONS πŸ’œ

These are the options that namespace ensemble create and namespace ensemble configure support, and they control how an ensemble command behaves. Buckle up, there's a few:

  • -map β€” When it's non-empty, this option hands over a dictionary that maps subcommand names to a list of prefix words, which get substituted in place of the ensemble command and subcommand words. (Similar vibe to an alias created with interp alias β€” the words are not reparsed after substitution.) If the first word of any target isn't fully qualified when you set it, it's assumed to be relative to the current namespace, and gets changed to be exactly that β€” meaning it's always fully qualified when you read it back, always πŸ’–. When this option is empty, the mapping goes from the local name of the subcommand to its fully-qualified name. Also note: when this option is non-empty and the -subcommands option is empty, the ensemble subcommand names will be exactly those words that have mappings in the dictionary. Exactly those. No extras πŸ‘‘.
  • -parameters β€” gives a list of named arguments (the names get used during generation of error messages) that are passed by the caller of the ensemble between the name of the ensemble and the subcommand argument. By default it's the empty list. (Yes, this is the one that lets you slot stuff in the middle β€” see the example down below with do 1 plus [do 9 minus 7] πŸ“.)
  • -prefixes β€” this one (which is enabled by default, she's on by default, she's thriving) controls whether the ensemble command recognizes unambiguous prefixes of its subcommands. Turn it off and the ensemble command requires exact matching of subcommand names. No shortcuts, no vibes. 🎯
  • -subcommands β€” when non-empty, this lists exactly what subcommands are in the ensemble. The mapping for each of those commands will be either whatever is defined in the -map option, or to the command with the same name in the namespace linked to the ensemble. If this option is empty, the subcommands of the namespace will be either the keys of the dictionary listed in the -map option, or the exported commands of the linked namespace at the time of the invocation of the ensemble command. Timing matters, bestie ⏰.
  • -unknown β€” when non-empty, gives a partial command to handle the case where an ensemble subcommand isn't recognized and would otherwise generate an error. (All the words that are arguments to the ensemble command, including the fully-qualified name of the ensemble, get appended to it.) When empty β€” which is the default β€” an error (in the style of Tcl_GetIndexFromObj) is generated whenever the ensemble can't figure out how to implement a particular subcommand. More deets in UNKNOWN HANDLER BEHAVIOUR below πŸ‘‡.

And there's one extra option that namespace ensemble create allows:

  • -command β€” this write-only option lets the name of the ensemble created by namespace ensemble create be anything in any existing namespace. The default value is the fully-qualified name of the namespace in which the namespace ensemble create command was invoked.

Plus one extra option that namespace ensemble configure allows:

  • -namespace β€” this read-only option lets you retrieve the fully-qualified name of the namespace which the ensemble was created within. Read-only, so look but don't touch πŸ™ˆ.

🌸 UNKNOWN HANDLER BEHAVIOUR 🌸

If an unknown handler is specified for an ensemble, that handler gets called whenever the ensemble command would otherwise return an error, because it just can't decide which subcommand to invoke 😭. The exact conditions under which that happens are controlled by the -subcommands, -map and -prefixes options, as described above. (So go reread those, bestie, it's all connected.)

To execute the unknown handler, the ensemble mechanism takes the specified -unknown option and appends each argument of the attempted ensemble command invocation to it β€” including the ensemble command itself, expressed as a fully qualified name πŸ’…. It invokes the resulting command in the scope of the attempted call. Then: if the execution of the unknown handler terminates normally, the ensemble engine reparses the subcommand (as described below) and tries to dispatch it again β€” which is ideal for when the ensemble's configuration has been updated by the unknown subcommand handler, chef's kiss πŸ§‘β€πŸ³. Any other kind of termination of the unknown handler is treated as an error. Periodt.

The result of the unknown handler is expected to be a list β€” and it is an error if it isn't, no cap. If that list is an empty list, the ensemble command attempts to look up the original subcommand again, and if it's still not found this time, an error gets generated just as if the -unknown handler wasn't there at all. Which means: for any particular invocation of an ensemble, its unknown handler will be called at most once πŸ‘‘. That's the whole point though β€” it makes it easy for the unknown handler to update the ensemble or its backing namespace so as to provide an implementation of the desired subcommand and reparse. Iconic behaviour honestly.

When the result is a non-empty list, the words of that list are used to replace the ensemble command and subcommand, exactly as if they'd been looked up in the -map. It's up to the unknown handler to supply all the namespace qualifiers if the implementing subcommand isn't in the namespace of the caller of the ensemble command. Also, note this: when ensemble commands are chained β€” like, say, if you make one of the commands that implement an ensemble subcommand into an ensemble itself, in a manner similar to the text widget's tag and mark subcommands β€” then the rewrite happens in the context of the caller of the outermost ensemble. Which is to say: ensembles do not in themselves place any namespace contexts on the Tcl call stack. Nothing. Zero. πŸ«₯

Where an empty -unknown handler is given (that's the default, remember), the ensemble command generates an error message based on the list of commands the ensemble has defined (formatted similarly to the error message from Tcl_GetIndexFromObj). And this is the error that gets thrown when the subcommand is still not recognized during reparsing. Also, heads up: it is an error for an -unknown handler to delete its namespace. Don't do that. Seriously 😭.


✨ EXAMPLES ✨

Create a namespace containing a variable and an exported command:

namespace eval foo {
    variable bar 0
    proc grill {} {
        variable bar
        puts "called [incr bar] times"
    }
    namespace export grill
}

Call the command defined in the previous example in various ways:

# Direct call
::foo::grill

# Use the command resolution path to find the name
namespace eval boo {
    namespace path ::foo
    grill
}

# Import into current namespace, then call local alias
namespace import foo::grill
grill

# Create two ensembles, one with the default name and one with a
# specified name.  Then call through the ensembles.
namespace eval foo {
    namespace ensemble create
    namespace ensemble create -command ::foobar
}
foo grill
foobar grill

Look up where the command imported in the previous example came from:

puts "grill came from [namespace origin grill]"

Remove all imported commands from the current namespace:

namespace forget {*}[namespace import]

Create an ensemble for simple working with numbers, using the -parameters option to allow the operator to be put between the first and second arguments:

namespace eval do {
    namespace export *
    namespace ensemble create -parameters x
    proc plus  {x y} {expr { $x + $y }}
    proc minus {x y} {expr { $x - $y }}
}

# In use, the ensemble works like this:
puts [do 1 plus [do 9 minus 7]]

πŸ¦‹ SEE ALSO πŸ¦‹


πŸ’– KEYWORDS πŸ’–

  • command
  • ensemble
  • exported
  • internal
  • variable

And that's the whole page, bestie, we did it πŸŽ€πŸŒˆβœ¨ This one's from the Tcl crew, version 8.5, living in the namespace(3tcl) manual page. Go forth and ensemble responsibly, you absolute queen πŸ‘‘πŸ’…πŸ«Ά

πŸ“¦ where this page comes from
  • ubuntu stonking: tcl9.0-doc 9.0.4+dfsg-1
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms