Python and TCL
2 July 2008
I have had to use the TCL programming language recently, I don't know it well yet, and I have found the quickest way at the moment is to prototype in Python and then edit it into TCL code. This way I know the logic is sound, and therefore logic errors are not mixed in with syntax errors.
in the following example, I had a sequential list of numbers in TCL (which were unique ids of XML elements), and for a given number I had to find the nearest numbers on either side.
"""Nearest Neighbours in a list of numbers."""
def nearestneighbours(numlist, number):
"""For a given number, find the nearest lower and higher numbers in
a given (ordered) list of numbers."""
left = None
right = float('inf')
for i in numlist:
if i < number and i > left:
left = i
if i > number and i < right:
right = i
return (left, right)
def main():
"""Demo when called directly."""
mylist = [58163, 62140, 66139, 70280, 74371,
78525, 82426, 86584, 90650, 94749]
number = 67000
lower, higher = nearestneighbours(mylist, number)
print "Lower:", lower
print "Higher:", higher
if __name__ == "__main__":
main()
We have the function working as we want to, so now we can try to rewrite the code into TCL:
# Nearest Neighbours in a list of numbers.
proc nearestneighbours {numlist number} {
# For a given number, find the nearest lower and higher numbers in
# a given (ordered) list of numbers.
set left 0
set right 1000000000
foreach i $numlist {
if {[expr $i < $number]} {if {[expr $i > $left]} {set left $i}} elseif {
[expr $i > $number]} {if {[expr $i < $right]} {set right $i}}
} ;# end foreach
set nearest [list $left $right]
return $nearest
} ;# end proc findnearest
proc main {} {
# Demo when called directly.
set mylist [list "58163" "62140" "66139" "70280" "74371" "78525" "82426" "86584"
"90650" "94749"]
set number 67000
set highlow [nearestneighbours $mylist $number]
puts "Lower: [lindex $highlow 0]"
puts "Higher: [lindex $highlow 1]"
} ;# end proc main
main
This works great.
However, I wrote the above Python code in a verbose way because I was sure I could replicate it in TCL, in a Python program, I can just use the Python list's sort method to find the neighbours.
def nearestneighbours(numlist, number):
"""For a given number, find the nearest lower and higher numbers in
a given (ordered) list of numbers."""
numlist.append(number)
numlist.sort()
return(numlist[numlist.index(number)-1],
numlist[numlist.index(number)+1])
This works exactly the same as the much more long winded version at the start of this post. How does one do this in TCL? Well rewriting the Python gives us:
proc nearestneighbours {numlist number} {
# For a given number, find the nearest higher and lower numbers in
# a given (ordered) list of numbers.
lappend numlist $number
set numlist [lsort -integer $numlist]
return [list [lindex $numlist [expr [lsearch $numlist $number] -1]]
[lindex $numlist [expr [lsearch $numlist $number] +1]]]
} ;# end proc findnearest
This seems to work fine too, which is the preferred TCL way, I'm not sure.



1 Andrew West says...
Both the Python and the Tcl example could do with error checking. While at first this may not seem on topic with the post I think it better shows the differences between Python and Tcl, and also one of the many things I dislike about Tcl.
For example, given a list of "1 2 3 4" Python
Tcl
Returns -1 in both languages, as you'd expect. But now what happens with each language when you try accessing a list index that doesn't exist?
Python
Throws a list index out of range exception
Tcl
Returns nothing, no error just blank string.
And it should be noted that Tcl, of course, allows blank items in a list. So did our lindex call returned blank, did it fail or return the blank element we where looking for? Who knows.
Now Tcl does support try/catch exception style programming, but from my experience it doesn't seem to use this in the base language. Errors go unchecked and can propagate through your code with careless programming. Where as with Python, exceptions get thrown and will propagate up through your code.
No matter the language you should be doing error checking, but with Tcl it seems a constant struggle compared to other languages with can be more lenient about where you check for the error.
Posted at 6:51 p.m. on July 6, 2008
2 Christopher Thoday says...
A single test is not sufficient to give you confidence that the algorithm is working. You should make 'number' an argument of 'main' so that you can test some boundary conditions, such as the first and last numbers and with 'number' equal to one of the numbers in the list.
The Tcl interpreter is so primitive that you have to use a lot of brackets to tell it what to do. This makes the code much harder to read and understand. The only time that I would ever consider using Tcl is in conjunction with the Tk toolkit and that does not fit very well into a modern GUI interface such as Gnome. It does have a powerful Canvas widget but I suspect that pyGame is just as good. If need a lightweight embedded scripting language then Lua might be better than Tcl.
One of the advantages of Python is the huge range of modules, both official and unofficial, that are available. However, you have to be careful to understand how to use them. In the second example the 'index' function will fail if 'number' is not in the list. You have to be careful with indexing as -1 is not to the left of 0 but is the last item in the list.
One of the problems with Python is that it does very little checking at compile time. Consequently, errors can go undetected if they occur in branches of the code that were not covered during testing. Although it is not the complete answer I recommend pyflakes as a useful tool.
Posted at 4:14 p.m. on July 12, 2008
3 Åke Forslund says...
I'm pretty much a novice in both of these languages but I find them both easy to use and preform the tasks I give them. However I rarely use them for the same tasks.
Python I use for it's ease of use and huge range of modules, the program and scripts I create with it are mostly for a specific task (serial communication with some hardware with pySerial, encoding images with pyImage or using the fabolus regExp-engine to rip summarize information. I started with python about six months ago (inspired by this blog) so I probably have a lot more to learn both about the language and the correct usage of it.
TCL on the other hand I mainly use when it is embedded in an other application which seem to be the languages' primary function (Tool Control Language). It's in Mentor Graphics ModelSim (letting the user control and observe simulations of digital electronics) it's in Atmel's SAM-BA to automate programming sequences for their ARM-CPUs, etc. I also use it to make quick (and crude) GUIs for my python commandline apps using the Tk-extensions. I'm an engineer my GUIs won't look pretty no matter what library I use ;-)
Posted at 9:29 p.m. on July 13, 2008
4 Paddy3118 says...
Hi, I too work with Electronic Design Automation tools, where Tcl is used extensively. I tend to only occasionally have to write in Tcl and so find the TclTutor utility: http://www.msen.com/~clif/TclTutorTour.html, quite useful.
Posted at 1:03 a.m. on July 18, 2008
5 PataElmo says...
I learned TCL first so I have an original bias towards it as a better language. I really fell in love with it too because I'm an EE at heart, and like assembly language for it's simplicity but like high level languages for their power. I love TCL for it's simple core with powerful functions.
I looked into Python after working with TCL and was turned off by the formatting of the language. I don't like the tab / spacing requirements. I tab a lot, but there are few times when it makes code too spaced out.
Also as a final note, like any loose scripting language the cleanliness of the code is how YOU write it. You can do a complex comparison inside an if without an expr.
} ;# end foreach
can be: foreach i $numlist {
}
That all being said, I am actually starting to learn Python, because it does have the advantage of handling data more efficiently. As well as being more wide-spread. But I think I will still love TCL for it's simplicity and ease of debug. The tabbing issue also makes it harder to be able to copy and paste code for testing on the interpreter or typing it in manually.
Posted at 7:36 p.m. on April 28, 2009
6 Steve H says...
You like the convenience of Python's list indexing functions, but it has led you to write inefficient code. You do two searches of your list to find the index of your desired number, where one would suffice. The relative unwieldiness of the corresponding Tcl code can be seen as a tip-off to this inefficiency. Here's another Tcl version of your code that is more efficient and looks a bit nicer:
package require Tcl 8.5 proc nearestneighbours {numlist number} { # For a given number, find the nearest higher and lower numbers in # a given (ordered) list of numbers. set numlist [lsort -integer -unique [concat $numlist $number]] set num [lsearch $numlist $number] foreach {left num right} [lrange $numlist $num-1 $num+1] {} return [list $left $right] } ;# end proc nearestneighbours proc main {} { # Demo when called directly. set mylist [list 58163 62140 66139 70280 74371 78525 82426 86584 90650 94749] set number 67000 foreach {low high} [nearestneighbours $mylist $number] {} puts "Lower: $low" puts "Higher: $high" } ;# end proc main mainPosted at 4:34 a.m. on May 30, 2009