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

numlist.index(5)

Tcl

lsearch $numlist 5

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

numlist[-1]

Throws a list index out of range exception

Tcl

lindex $numlist -1

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.

  • Paddy.

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.

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}}

System Message: WARNING/2 (<string>, line 10)

Block quote ends without a blank line; unexpected unindent.

} ;# end foreach

can be: foreach i $numlist {

System Message: ERROR/3 (<string>, line 14)

Unexpected indentation.
if {($i < $number) && ($i > $left)} {
set left $i
} else if {($i > $number) && ($i < $right)} {
set right $i

System Message: WARNING/2 (<string>, line 18)

Definition list ends without a blank line; unexpected unindent.

}

System Message: WARNING/2 (<string>, line 19)

Block quote ends without a blank line; unexpected unindent.

}

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

 main

Posted at 4:34 a.m. on May 30, 2009


What do you have to say?

Show Editing Help

About

Hello, my name is Zeth, I'll be your host here.

Command Line Warriors is about taking control of your own technology, it looks at our experiences of computing; especially using GNU/Linux, the Python programming language, the command-line and issues such as techno-ethics, best practices and whatever is cool now. If you take control of your technology then you are a Warrior too!

This site is your site too which means that you can contribute and get involved. You can leave comments using the facility provided. For me, the comments and discussions are by far the best part of the site. So please do have your say!

Latest Discussions

Cupcake

July 31, 2010
Good post! You helped me a lot with my school project! CountryField(blank = True) < (K)
Countries in Django

LeshaShampoo

July 30, 2010
it was very interesting to read commandline.org.uk I want to quote your post in my blog. It can? And you et an account on Twitter?
Email Syntax Check in Python

vemma2018

July 30, 2010
I find myself coming to your blog more and more often to the point where my visits are almost daily now!
On Comment Spam

layecenda

July 30, 2010
Hello. And Bye.test :) http://idfjhvihdfiphvlajbvhalibv.com
PuTTY Series: Adding PuTTY to your system path

scuba

July 30, 2010
I’ve been visiting your blog for a while now and I always find a gem in your new posts. Thanks for sharing.
On Comment Spam

Businesking

July 30, 2010
Great site and articles for hack for win, I said Amazing post
How not to program WSGI

Tehnoking

July 30, 2010
This is Great post to learn about the hack Thumbs-up for you :D
How not to program WSGI

Syabiltech

July 30, 2010
I think this articles for master...because very hard to learning, As blogger beginners like me.
How not to program WSGI

coffeeatea

July 30, 2010
Are you looking for coffee gifts? We can tell you more about the coffee gifts including coffee machines and coffee pods.
Introducing Soturi - yet another Django blog application

noni juice

July 30, 2010
I just sent this post to a bunch of my friends as I agree with most of what you’re saying here and the way you’ve presented it is awesome.
On Comment Spam

Dion Moult

July 29, 2010
What I do know is that ever since I tried out Opera and put their tab bar on the left as a column, I've loved that layout. Back on Firefox ...
We need a thoughout integration of the desktop and the web - not Tab Candy superfast jellyfish

ZonaEntertainment

July 29, 2010
Wow useful articles, I'm read to learn about this and now I bookmark this to my Facebook, thanks for share!
How not to program WSGI

Giacomo

July 29, 2010
Honestly, I think both Mozilla and you are wrong :) This sort of concept adds overhead. A user would have to manage all this crap, constantly dragging and dropping, creating ...
We need a thoughout integration of the desktop and the web - not Tab Candy superfast jellyfish

Matija "hook" Šuklje

July 29, 2010
As a minimalist, you'll probybly moan if I mention KDE, but I'll do so anyway ;) The future I want (and actually see slowly fold out before me) is to ...
We need a thoughout integration of the desktop and the web - not Tab Candy superfast jellyfish

tahitian noni

July 28, 2010
Thank You For This Blog, was added to my bookmarks.
On Comment Spam

Rick

July 28, 2010
I already have piles. It's called A New Window.
We need a thoughout integration of the desktop and the web - not Tab Candy superfast jellyfish

Tech News

July 25, 2010
Thanks for this short tutorial...was auto-FTPing my files from my appserver to webserver for my tech news website. Everything was OK until someone hacked it. Hosting provider is now recommending ...
SFTP in Python: Really Simple SSH

naypalm

July 24, 2010
During the past 3-4 years, I and many others have enjoyed unlimited 2G/3G internet. But ever since the massive cult-like following of i Phone users in the US, most cellular ...
Calling time on mobile internet nonsense?

Steve

July 15, 2010
Very occasionally, you will run into a Java program that uses a lot of memory just to hold all the classes used. It turns out that the JVM uses a ...
Three classic command line tips

no

July 14, 2010
1. number one 2. number two 4. number four 3. number three 6. number six # first # second ## second-ay ## second-bee ### second-bee-one ### second-bee-two
An Introduction to ReStructuredText