1namespace(n) Tcl Built-In Commands namespace(n)
2
3
4
5______________________________________________________________________________
6
8 namespace - create and manipulate contexts for commands and variables
9
11 namespace ?option? ?arg ...?
12_________________________________________________________________
13
14
16 The namespace command lets you create, access, and destroy separate
17 contexts for commands and variables. See the section WHAT IS A NAMES‐
18 PACE? below for a brief overview of namespaces. The legal values of
19 option are listed below. Note that you can abbreviate the options.
20
21 namespace children ?namespace? ?pattern?
22 Returns a list of all child namespaces that belong to the names‐
23 pace namespace. If namespace is not specified, then the chil‐
24 dren are returned for the current namespace. This command
25 returns fully-qualified names, which start with a double colon
26 (::). If the optional pattern is given, then this command
27 returns only the names that match the glob-style pattern. The
28 actual pattern used is determined as follows: a pattern that
29 starts with double colon (::) is used directly, otherwise the
30 namespace namespace (or the fully-qualified name of the current
31 namespace) is prepended onto the pattern.
32
33 namespace code script
34 Captures the current namespace context for later execution of
35 the script script. It returns a new script in which script has
36 been wrapped in a namespace inscope command. The new script has
37 two important properties. First, it can be evaluated in any
38 namespace and will cause script to be evaluated in the current
39 namespace (the one where the namespace code command was
40 invoked). Second, additional arguments can be appended to the
41 resulting script and they will be passed to script as additional
42 arguments. For example, suppose the command set script [names‐
43 pace code {foo bar}] is invoked in namespace ::a::b. Then eval
44 "$script x y" can be executed in any namespace (assuming the
45 value of script has been passed in properly) and will have the
46 same effect as the command ::namespace eval ::a::b {foo bar x
47 y}. This command is needed because extensions like Tk normally
48 execute callback scripts in the global namespace. A scoped com‐
49 mand captures a command together with its namespace context in a
50 way that allows it to be executed properly later. See the sec‐
51 tion SCOPED SCRIPTS for some examples of how this is used to
52 create callback scripts.
53
54 namespace current
55 Returns the fully-qualified name for the current namespace. The
56 actual name of the global namespace is ``'' (i.e., an empty
57 string), but this command returns :: for the global namespace as
58 a convenience to programmers.
59
60 namespace delete ?namespace namespace ...?
61 Each namespace namespace is deleted and all variables, proce‐
62 dures, and child namespaces contained in the namespace are
63 deleted. If a procedure is currently executing inside the
64 namespace, the namespace will be kept alive until the procedure
65 returns; however, the namespace is marked to prevent other code
66 from looking it up by name. If a namespace doesn't exist, this
67 command returns an error. If no namespace names are given, this
68 command does nothing.
69
70 namespace eval namespace arg ?arg ...?
71 Activates a namespace called namespace and evaluates some code
72 in that context. If the namespace does not already exist, it is
73 created. If more than one arg argument is specified, the argu‐
74 ments are concatenated together with a space between each one in
75 the same fashion as the eval command, and the result is evalu‐
76 ated.
77
78 If namespace has leading namespace qualifiers and any leading
79 namespaces do not exist, they are automatically created.
80
81 namespace exists namespace
82 Returns 1 if namespace is a valid namespace in the current con‐
83 text, returns 0 otherwise.
84
85 namespace export ?-clear? ?pattern pattern ...?
86 Specifies which commands are exported from a namespace. The
87 exported commands are those that can be later imported into
88 another namespace using a namespace import command. Both com‐
89 mands defined in a namespace and commands the namespace has pre‐
90 viously imported can be exported by a namespace. The commands
91 do not have to be defined at the time the namespace export com‐
92 mand is executed. Each pattern may contain glob-style special
93 characters, but it may not include any namespace qualifiers.
94 That is, the pattern can only specify commands in the current
95 (exporting) namespace. Each pattern is appended onto the names‐
96 pace's list of export patterns. If the -clear flag is given,
97 the namespace's export pattern list is reset to empty before any
98 pattern arguments are appended. If no patterns are given and
99 the -clear flag isn't given, this command returns the names‐
100 pace's current export list.
101
102 namespace forget ?pattern pattern ...?
103 Removes previously imported commands from a namespace. Each
104 pattern is a simple or qualified name such as x, foo::x or
105 a::b::p*. Qualified names contain double colons (::) and qual‐
106 ify a name with the name of one or more namespaces. Each quali‐
107 fied pattern is qualified with the name of an exporting names‐
108 pace and may have glob-style special characters in the command
109 name at the end of the qualified name. Glob characters may not
110 appear in a namespace name. For each simple pattern this com‐
111 mand deletes the matching commands of the current namespace that
112 were imported from a different namespace. For qualified pat‐
113 terns, this command first finds the matching exported commands.
114 It then checks whether any of those commands were previously
115 imported by the current namespace. If so, this command deletes
116 the corresponding imported commands. In effect, this un-does
117 the action of a namespace import command.
118
119 namespace import ?-force? ?pattern pattern ...?
120 Imports commands into a namespace. Each pattern is a qualified
121 name like foo::x or a::p*. That is, it includes the name of an
122 exporting namespace and may have glob-style special characters
123 in the command name at the end of the qualified name. Glob
124 characters may not appear in a namespace name. All the commands
125 that match a pattern string and which are currently exported
126 from their namespace are added to the current namespace. This
127 is done by creating a new command in the current namespace that
128 points to the exported command in its original namespace; when
129 the new imported command is called, it invokes the exported com‐
130 mand. This command normally returns an error if an imported
131 command conflicts with an existing command. However, if the
132 -force option is given, imported commands will silently replace
133 existing commands. The namespace import command has snapshot
134 semantics: that is, only requested commands that are currently
135 defined in the exporting namespace are imported. In other
136 words, you can import only the commands that are in a namespace
137 at the time when the namespace import command is executed. If
138 another command is defined and exported in this namespace later
139 on, it will not be imported.
140
141 namespace inscope namespace script ?arg ...?
142 Executes a script in the context of the specified namespace.
143 This command is not expected to be used directly by programmers;
144 calls to it are generated implicitly when applications use
145 namespace code commands to create callback scripts that the
146 applications then register with, e.g., Tk widgets. The names‐
147 pace inscope command is much like the namespace eval command
148 except that the namespace must already exist, and namespace
149 inscope appends additional args as proper list elements.
150 namespace inscope ::foo $script $x $y $z is equivalent to names‐
151 pace eval ::foo [concat $script [list $x $y $z]] thus additional
152 arguments will not undergo a second round of substitution, as is
153 the case with namespace eval.
154
155 namespace origin command
156 Returns the fully-qualified name of the original command to
157 which the imported command command refers. When a command is
158 imported into a namespace, a new command is created in that
159 namespace that points to the actual command in the exporting
160 namespace. If a command is imported into a sequence of names‐
161 paces a, b,...,n where each successive namespace just imports
162 the command from the previous namespace, this command returns
163 the fully-qualified name of the original command in the first
164 namespace, a. If command does not refer to an imported command,
165 the command's own fully-qualified name is returned.
166
167 namespace parent ?namespace?
168 Returns the fully-qualified name of the parent namespace for
169 namespace namespace. If namespace is not specified, the fully-
170 qualified name of the current namespace's parent is returned.
171
172 namespace qualifiers string
173 Returns any leading namespace qualifiers for string. Qualifiers
174 are namespace names separated by double colons (::). For the
175 string ::foo::bar::x, this command returns ::foo::bar, and for
176 :: it returns an empty string. This command is the complement
177 of the namespace tail command. Note that it does not check
178 whether the namespace names are, in fact, the names of currently
179 defined namespaces.
180
181 namespace tail string
182 Returns the simple name at the end of a qualified string. Qual‐
183 ifiers are namespace names separated by double colons (::). For
184 the string ::foo::bar::x, this command returns x, and for :: it
185 returns an empty string. This command is the complement of the
186 namespace qualifiers command. It does not check whether the
187 namespace names are, in fact, the names of currently defined
188 namespaces.
189
190 namespace which ?-command? ?-variable? name
191 Looks up name as either a command or variable and returns its
192 fully-qualified name. For example, if name does not exist in
193 the current namespace but does exist in the global namespace,
194 this command returns a fully-qualified name in the global names‐
195 pace. If the command or variable does not exist, this command
196 returns an empty string. If the variable has been created but
197 not defined, such as with the variable command or through a
198 trace on the variable, this command will return the fully-quali‐
199 fied name of the variable. If no flag is given, name is treated
200 as a command name. See the section NAME RESOLUTION below for an
201 explanation of the rules regarding name resolution.
202
204 A namespace is a collection of commands and variables. It encapsulates
205 the commands and variables to ensure that they won't interfere with the
206 commands and variables of other namespaces. Tcl has always had one
207 such collection, which we refer to as the global namespace. The global
208 namespace holds all global variables and commands. The namespace eval
209 command lets you create new namespaces. For example,
210 namespace eval Counter {
211 namespace export bump
212 variable num 0
213
214 proc bump {} {
215 variable num
216 incr num
217 }
218 }
219 creates a new namespace containing the variable num and the procedure
220 bump. The commands and variables in this namespace are separate from
221 other commands and variables in the same program. If there is a com‐
222 mand named bump in the global namespace, for example, it will be dif‐
223 ferent from the command bump in the Counter namespace.
224
225 Namespace variables resemble global variables in Tcl. They exist out‐
226 side of the procedures in a namespace but can be accessed in a proce‐
227 dure via the variable command, as shown in the example above.
228
229 Namespaces are dynamic. You can add and delete commands and variables
230 at any time, so you can build up the contents of a namespace over time
231 using a series of namespace eval commands. For example, the following
232 series of commands has the same effect as the namespace definition
233 shown above:
234 namespace eval Counter {
235 variable num 0
236 proc bump {} {
237 variable num
238 return [incr num]
239 }
240 }
241 namespace eval Counter {
242 proc test {args} {
243 return $args
244 }
245 }
246 namespace eval Counter {
247 rename test ""
248 }
249 Note that the test procedure is added to the Counter namespace, and
250 later removed via the rename command.
251
252 Namespaces can have other namespaces within them, so they nest hierar‐
253 chically. A nested namespace is encapsulated inside its parent names‐
254 pace and can not interfere with other namespaces.
255
257 Each namespace has a textual name such as history or ::safe::interp.
258 Since namespaces may nest, qualified names are used to refer to com‐
259 mands, variables, and child namespaces contained inside namespaces.
260 Qualified names are similar to the hierarchical path names for Unix
261 files or Tk widgets, except that :: is used as the separator instead of
262 / or .. The topmost or global namespace has the name ``'' (i.e., an
263 empty string), although :: is a synonym. As an example, the name
264 ::safe::interp::create refers to the command create in the namespace
265 interp that is a child of namespace ::safe, which in turn is a child of
266 the global namespace, ::.
267
268 If you want to access commands and variables from another namespace,
269 you must use some extra syntax. Names must be qualified by the names‐
270 pace that contains them. From the global namespace, we might access
271 the Counter procedures like this:
272 Counter::bump 5
273 Counter::Reset
274 We could access the current count like this:
275 puts "count = $Counter::num"
276 When one namespace contains another, you may need more than one quali‐
277 fier to reach its elements. If we had a namespace Foo that contained
278 the namespace Counter, you could invoke its bump procedure from the
279 global namespace like this:
280 Foo::Counter::bump 3
281
282 You can also use qualified names when you create and rename commands.
283 For example, you could add a procedure to the Foo namespace like this:
284 proc Foo::Test {args} {return $args}
285 And you could move the same procedure to another namespace like this:
286 rename Foo::Test Bar::Test
287
288 There are a few remaining points about qualified names that we should
289 cover. Namespaces have nonempty names except for the global namespace.
290 :: is disallowed in simple command, variable, and namespace names
291 except as a namespace separator. Extra colons in any separator part of
292 a qualified name are ignored; i.e. two or more colons are treated as a
293 namespace separator. A trailing :: in a qualified variable or command
294 name refers to the variable or command named {}. However, a trailing
295 :: in a qualified namespace name is ignored.
296
298 In general, all Tcl commands that take variable and command names sup‐
299 port qualified names. This means you can give qualified names to such
300 commands as set, proc, rename, and interp alias. If you provide a
301 fully-qualified name that starts with a ::, there is no question about
302 what command, variable, or namespace you mean. However, if the name
303 does not start with a :: (i.e., is relative), Tcl follows a fixed rule
304 for looking it up: Command and variable names are always resolved by
305 looking first in the current namespace, and then in the global names‐
306 pace. Namespace names, on the other hand, are always resolved by look‐
307 ing in only the current namespace.
308
309 In the following example,
310 set traceLevel 0
311 namespace eval Debug {
312 printTrace $traceLevel
313 }
314 Tcl looks for traceLevel in the namespace Debug and then in the global
315 namespace. It looks up the command printTrace in the same way. If a
316 variable or command name is not found in either context, the name is
317 undefined. To make this point absolutely clear, consider the following
318 example:
319 set traceLevel 0
320 namespace eval Foo {
321 variable traceLevel 3
322
323 namespace eval Debug {
324 printTrace $traceLevel
325 }
326 }
327 Here Tcl looks for traceLevel first in the namespace Foo::Debug. Since
328 it is not found there, Tcl then looks for it in the global namespace.
329 The variable Foo::traceLevel is completely ignored during the name res‐
330 olution process.
331
332 You can use the namespace which command to clear up any question about
333 name resolution. For example, the command:
334 namespace eval Foo::Debug {namespace which -variable traceLevel}
335 returns ::traceLevel. On the other hand, the command,
336 namespace eval Foo {namespace which -variable traceLevel}
337 returns ::Foo::traceLevel.
338
339 As mentioned above, namespace names are looked up differently than the
340 names of variables and commands. Namespace names are always resolved
341 in the current namespace. This means, for example, that a namespace
342 eval command that creates a new namespace always creates a child of the
343 current namespace unless the new namespace name begins with ::.
344
345 Tcl has no access control to limit what variables, commands, or names‐
346 paces you can reference. If you provide a qualified name that resolves
347 to an element by the name resolution rule above, you can access the
348 element.
349
350 You can access a namespace variable from a procedure in the same names‐
351 pace by using the variable command. Much like the global command, this
352 creates a local link to the namespace variable. If necessary, it also
353 creates the variable in the current namespace and initializes it. Note
354 that the global command only creates links to variables in the global
355 namespace. It is not necessary to use a variable command if you always
356 refer to the namespace variable using an appropriate qualified name.
357
359 Namespaces are often used to represent libraries. Some library com‐
360 mands are used so frequently that it is a nuisance to type their quali‐
361 fied names. For example, suppose that all of the commands in a package
362 like BLT are contained in a namespace called Blt. Then you might
363 access these commands like this:
364 Blt::graph .g -background red
365 Blt::table . .g 0,0
366 If you use the graph and table commands frequently, you may want to
367 access them without the Blt:: prefix. You can do this by importing the
368 commands into the current namespace, like this:
369 namespace import Blt::*
370 This adds all exported commands from the Blt namespace into the current
371 namespace context, so you can write code like this:
372 graph .g -background red
373 table . .g 0,0
374 The namespace import command only imports commands from a namespace
375 that that namespace exported with a namespace export command.
376
377 Importing every command from a namespace is generally a bad idea since
378 you don't know what you will get. It is better to import just the spe‐
379 cific commands you need. For example, the command
380 namespace import Blt::graph Blt::table
381 imports only the graph and table commands into the current context.
382
383 If you try to import a command that already exists, you will get an
384 error. This prevents you from importing the same command from two dif‐
385 ferent packages. But from time to time (perhaps when debugging), you
386 may want to get around this restriction. You may want to reissue the
387 namespace import command to pick up new commands that have appeared in
388 a namespace. In that case, you can use the -force option, and existing
389 commands will be silently overwritten:
390 namespace import -force Blt::graph Blt::table
391 If for some reason, you want to stop using the imported commands, you
392 can remove them with a namespace forget command, like this:
393 namespace forget Blt::*
394 This searches the current namespace for any commands imported from Blt.
395 If it finds any, it removes them. Otherwise, it does nothing. After
396 this, the Blt commands must be accessed with the Blt:: prefix.
397
398 When you delete a command from the exporting namespace like this:
399 rename Blt::graph ""
400 the command is automatically removed from all namespaces that import
401 it.
402
404 You can export commands from a namespace like this:
405 namespace eval Counter {
406 namespace export bump reset
407 variable Num 0
408 variable Max 100
409
410 proc bump {{by 1}} {
411 variable Num
412 incr Num $by
413 Check
414 return $Num
415 }
416 proc reset {} {
417 variable Num
418 set Num 0
419 }
420 proc Check {} {
421 variable Num
422 variable Max
423 if {$Num > $Max} {
424 error "too high!"
425 }
426 }
427 }
428 The procedures bump and reset are exported, so they are included when
429 you import from the Counter namespace, like this:
430 namespace import Counter::*
431 However, the Check procedure is not exported, so it is ignored by the
432 import operation.
433
434 The namespace import command only imports commands that were declared
435 as exported by their namespace. The namespace export command specifies
436 what commands may be imported by other namespaces. If a namespace
437 import command specifies a command that is not exported, the command is
438 not imported.
439
441 The namespace code command is the means by which a script may be pack‐
442 aged for evaluation in a namespace other than the one in which it was
443 created. It is used most often to create event handlers, Tk bindings,
444 and traces for evaluation in the global context. For instance, the
445 following code indicates how to direct a variable trace callback into
446 the current namespace:
447 namespace eval a {
448 variable b
449 proc theTraceCallback { n1 n2 op } {
450 upvar 1 $n1 var
451 puts "the value of $n1 has changed to $var"
452 return
453 }
454 trace variable b w [namespace code theTraceCallback]
455 }
456 set a::b c
457 When executed, it prints the message:
458 the value of a::b has changed to c
459
461 Create a namespace containing a variable and an exported command:
462 namespace eval foo {
463 variable bar 0
464 proc grill {} {
465 variable bar
466 puts "called [incr bar] times"
467 }
468 namespace export grill
469 }
470
471 Call the command defined in the previous example in various ways.
472 # Direct call
473 foo::grill
474
475 # Import into current namespace, then call local alias
476 namespace import foo::grill
477 grill
478
479 Look up where the command imported in the previous example came from:
480 puts "grill came from [namespace origin grill]"
481
482
484 variable(n)
485
486
488 exported, internal, variable
489
490
491
492Tcl 8.0 namespace(n)