ZetCode

Tcl packages and modules

last modified November 24, 2026 Tcl 8.6

A larger Tcl program is not one long script. It is a set of files, each holding procedures for one job, and the main script loads the files it needs. Tcl formalizes this with packages: a file declares which package and version it provides, another file says where to find it, and the program asks for it by name. The interpreter then loads it once, no matter how many places ask.

This article starts with the two commands at the heart of the system, package require and package provide, then explains the pkgIndex.tcl file and the auto_path variable that together make loading automatic. It builds a small package from scratch, uses a namespace as a module boundary, and closes with a short look at Tcllib, the standard collection of Tcl packages.

Loading a package with package require

The package command manages the packages known to the interpreter. In the form package require name ?version? it makes sure that a package is loaded and returns the version that was actually loaded. The version argument is a minimum, not an exact match: a script that needs 8.5 is satisfied by 8.6. If the version cannot be met, the command raises an error instead of returning.

require_demo.tcl
puts "Tcl version: [package require Tcl]"
puts "at least 8.5: [package require Tcl 8.5]"

set rc [catch {package require Tcl 9.0} msg]
puts "Tcl 9 available: [expr {$rc == 0}]"
puts "message: $msg"

The first two calls both return 8.6.12, because that is the version present and it satisfies the lower requirement. The third call asks for a version that does not exist on this machine, so catch reports failure and the error message names both the version that is available and the one that was needed. The same pattern works for any package, which is why a library often begins with package require Tcl 8.5 to state its minimum interpreter.

$ tclsh require_demo.tcl
Tcl version: 8.6.12
at least 8.5: 8.6.12
Tcl 9 available: 0
message: version conflict for package "Tcl": have 8.6.12, need 9.0

Declaring a package with package provide

The other half of the contract is package provide name version. A module file ends with this call, so that loading the file registers the package in the interpreter. After that, package require returns the version without loading anything again. The next listing is a complete module file; it is meant to be loaded, not run on its own.

greet.tcl
proc greet {name} {
    return "Hello there, $name!"
}

package provide greeting 1.0

The file defines one procedure and declares the package version. Nothing happens until some script loads it: source evaluates the file in the current interpreter, and the final line records the package. A program then uses package require to check that the package is there. This two-step arrangement means a module can also be loaded by hand during development, while the require call stays in the program.

provide_demo.tcl
source greet.tcl

puts "provided: [package require greeting]"
puts [greet "Jane"]
puts "asking again is free: [package require greeting 1.0]"

After the source, the package is registered, so require simply returns 1.0. The procedure is an ordinary global command and is called by name. The third call repeats the request with an explicit version and still returns 1.0, because a loaded package that satisfies the requirement is not reloaded. That is the property that makes packages safe to require from every file that needs them.

$ tclsh provide_demo.tcl
provided: 1.0
Hello there, Jane!
asking again is free: 1.0

The pkgIndex.tcl file

Requiring a package by name only works if the interpreter can find it. A directory that holds packages contains a file called pkgIndex.tcl, and the loader reads it to learn which versions are available and which script loads each one. The file is a normal Tcl script made of package ifneeded lines.

pkgIndex.tcl
package ifneeded greeting 1.0 [list source [file join $dir greeting.tcl]]

Each line ties one version of one package to the script that loads it. The variable $dir is not set by the file; the package loader sets it to the directory that contains the index, so the entry keeps working when the whole tree is moved. The [list ...] wrapper keeps the loader script a single word, which matters when the path contains spaces. The same mechanism works without any file at all, which is a convenient way to see what ifneeded does.

ifneeded_demo.tcl
package ifneeded report 1.0 {
    puts "running the loader script"
    package provide report 1.0
}
puts "known versions: [package versions report]"
puts "require returned: [package require report]"

The three-argument form registers the package with a loader script instead of loading it. package versions then reports 1.0, because the version is known but not yet present. When require runs, it evaluates the script, the script announces itself and provides the version, and the require call returns 1.0. A loader script that forgets the package provide line fails, which is the most common mistake in a hand-written index.

$ tclsh ifneeded_demo.tcl
known versions: 1.0
running the loader script
require returned: 1.0

Extending auto_path

The directories that the loader searches are stored in the global list auto_path. The interpreter fills it at startup from the installation and from the TCLLIBPATH environment variable, and a script may append its own directory. Appending is enough; the loader scans the new directory the next time a package is required.

auto_path_demo.tcl
puts "auto_path holds [llength $auto_path] directories"

foreach dir $auto_path {
    if {[string match *tcl8.6* $dir]} {
        puts "  library: $dir"
    }
}

set mine [file join [pwd] modules]
lappend auto_path $mine
puts "mine is at index [lsearch -exact $auto_path $mine]"

The loop filters the list with a glob pattern and prints only the entries that belong to the Tcl 8.6 installation; the count and the exact paths depend on the system. The last two lines append a modules directory next to the script and confirm its position. Because lappend adds to the end, the new directory is searched after the system ones, which is usually what a project wants for its own private packages.

$ tclsh auto_path_demo.tcl
auto_path holds 8 directories
  library: /usr/share/tcltk/tcl8.6
  library: /usr/lib/tcltk/tcl8.6
mine is at index 8

Building a small package directory

The pieces can now be put together. The next script creates a directory with one module and one index, adds the directory to auto_path and requires the package. It writes the files with ordinary Tcl channels, so the whole package is visible in the script that builds it.

build_pkg.tcl
set root [file join [pwd] demo_pkg]
file mkdir $root

set f [open [file join $root greeting.tcl] w]
puts $f {proc greet {name} {
    return "Hello there, $name!"
}}
puts $f {package provide greeting 1.0}
close $f

set f [open [file join $root pkgIndex.tcl] w]
puts $f {package ifneeded greeting 1.0 [list source [file join $dir greeting.tcl]]}
close $f

lappend auto_path $root
puts "loaded: [package require greeting]"
puts [greet "Jane"]
puts "path ends with: [file tail [lindex $auto_path end]]"

The module file is written in two pieces because the body of the procedure contains braces; keeping the outer text in braces leaves the inner quotes and variables untouched, so the file contains exactly the procedure definition. The index is a single line. After lappend, the require call searches the new directory, reads the index and sources the module. The procedure is then a normal command. In a real project the files would live in version control and the script would only add the directory to the path.

$ tclsh build_pkg.tcl
loaded: 1.0
Hello there, Jane!
path ends with: demo_pkg

Namespaces as module boundaries

A package that defines many procedures pollutes the global namespace, and two packages may both want a procedure called hello. The namespace command solves this: procedures and variables live inside a named container, are called with a qualified name, and cannot collide with anything outside it. A package file usually wraps its whole content in one namespace eval block.

namespace_pkg.tcl
namespace eval greeting {
    variable defaultName "friend"

    proc hello {name} {
        variable defaultName
        if {$name eq ""} {
            set name $defaultName
        }
        return "Hello there, $name!"
    }

    package provide greeting 2.0
}

puts [greeting::hello "Jane"]
puts [greeting::hello ""]
puts "command: [namespace which greeting::hello]"
puts "provided: [package require greeting]"

The procedure is created as greeting::hello, and the namespace variable defaultName is visible to it through the variable declaration. Calling the command with an empty name uses that default, while the first call overrides it. namespace which prints the fully qualified name, which is useful when a command has been imported or renamed. package provide works inside the block because packages are registered in a single global registry, not per namespace.

$ tclsh namespace_pkg.tcl
Hello there, Jane!
Hello there, friend!
command: ::greeting::hello
provided: 2.0

package forget and package names

A long-running interpreter, such as an embedded Tcl shell or a test runner, may need to drop a package and load a newer build. The command for that is package forget name, which removes the provided version and the in-memory index entry. It does not remove the files and it does not delete the procedures the package defined; the next require reads the index again and sources the file once more.

forget_demo.tcl
set root [file join [pwd] forget_pkg]
file mkdir $root

set f [open [file join $root tempconvert.tcl] w]
puts $f {proc c2f {celsius} {
    expr {$celsius * 9 / 5 + 32}
}}
puts $f {package provide tempconvert 1.0}
close $f

set f [open [file join $root pkgIndex.tcl] w]
puts $f {package ifneeded tempconvert 1.0 [list source [file join $dir tempconvert.tcl]]}
close $f

lappend auto_path $root
puts "loaded: [package require tempconvert]"
puts "100 C is [c2f 100] F"

package forget tempconvert
puts "still known: [expr {[lsearch -exact [package names] tempconvert] >= 0}]"
puts "c2f still callable: [c2f 0]"

set rc [catch {package require tempconvert} version]
puts "require again: code $rc, version $version"

The package is a one-line temperature converter, and the script uses it immediately after requiring it. After package forget, the name is gone from package names but c2f still exists, which shows that forgetting is a registry operation, not an unload. The last require succeeds again with code 0 and version 1.0 because the loader finds the index on auto_path a second time. To truly reload changed code, a script has to forget the package, remove or rename its commands, and then require it again.

$ tclsh forget_demo.tcl
loaded: 1.0
100 C is 212 F
still known: 0
c2f still callable: 32
require again: code 0, version 1.0

Tcllib in brief

Most real Tcl programs need JSON, CSV files, string utilities or a logger, and those are not part of the core interpreter. They live in Tcllib, a large collection of pure Tcl packages maintained by the Tcl community. It installs its modules under a directory that is added to auto_path, and each module is found through the same pkgIndex.tcl mechanism, so it needs no special support in the interpreter: an ordinary package require finds its modules.

The collection is organised by topic. The json and csv modules read and write those formats, struct::list and struct::set add list and set operations, fileutil handles recursive copies and temporary files, textutil collects string helpers, logger provides a small logging framework, cmdline parses command-line options, and base64, sha1 and md5 cover encoding and hashing. Each module has its own name, so a program requires only the parts it uses.

On Debian and Ubuntu the collection is the tcllib package in the distribution; other systems build it with the installer that ships with the project. Tcllib is not installed on the machine used for this series, so the examples here avoid it and the modules are described rather than demonstrated. Checking whether a module is present is still a one-liner with package require, wrapped in catch when the answer may be no. The auto_load page explains how Tcl locates unknown commands, which is the same search that packages use.

Source

The Tcl 8.6 manual covers the package system in detail, including version comparison rules, the package unknown hook and the exact search order used by package require.

This article covered the package system from both sides: requiring a package, providing one, writing a pkgIndex.tcl entry, extending auto_path, and using a namespace so that a module keeps its names to itself. It also showed what package forget really does and where Tcllib fits in. Continue with the Tcl namespace page for the full set of namespace subcommands, or with the processes article to see how packages and external programs work together.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.