Tcl - Namespaces


Advertisements

Namespace is a container for set of identifiers that is used to group variables and procedures. Namespaces are available from Tcl version 8.0. Before the introduction of the namespaces, there was single global scope. Now with namespaces, we have additional partitions of global scope.

Creating Namespace

Namespaces are created using the namespace command. A simple example for creating namespace is shown below −

#!/usr/bin/tclsh

namespace eval MyMath {
  # Create a variable inside the namespace
  variable myResult
}

# Create procedures inside the namespace
proc MyMath::Add {a b } {  
  set ::MyMath::myResult [expr $a + $b]
}
MyMath::Add 10 23

puts $::MyMath::myResult

When the above code is executed, it produces the following result −

33

In the above program, you can see there is a namespace with a variable myResult and a procedure Add. This makes it possible to create variables and procedures with the same names under different namespaces.

Nested Namespaces

Tcl allows nesting of namespaces. A simple example for nesting namespaces is given below −

#!/usr/bin/tclsh

namespace eval MyMath {
   # Create a variable inside the namespace
   variable myResult
}

namespace eval extendedMath {
   # Create a variable inside the namespace
   namespace eval MyMath {
      # Create a variable inside the namespace
      variable myResult
   }
}
set ::MyMath::myResult "test1"
puts $::MyMath::myResult
set ::extendedMath::MyMath::myResult "test2"
puts $::extendedMath::MyMath::myResult

When the above code is executed, it produces the following result −

test1
test2

Importing and Exporting Namespace

You can see in the previous namespace examples, we use a lot of scope resolution operator and it's more complex to use. We can avoid this by importing and exporting namespaces. An example is given below −

#!/usr/bin/tclsh

namespace eval MyMath {
   # Create a variable inside the namespace
   variable myResult
   namespace export Add
}

# Create procedures inside the namespace
proc MyMath::Add {a b } {  
   return [expr $a + $b]
}

namespace import MyMath::*
puts [Add 10 30]

When the above code is executed, it produces the following result −

40

Forget Namespace

You can remove an imported namespace by using forget subcommand. A simple example is shown below −

#!/usr/bin/tclsh

namespace eval MyMath {
   # Create a variable inside the namespace
   variable myResult
   namespace export Add
}

# Create procedures inside the namespace
proc MyMath::Add {a b } {  
   return [expr $a + $b]
}
namespace import MyMath::*
puts [Add 10 30]
namespace forget MyMath::*

When the above code is executed, it produces the following result −

40
Advertisements