• Zeth will be attending PyCon UK on the 12th to 14th September 2008.

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


What do you have to say?

Show Editing Help


PyCon UK

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

Naib

August 27, 2008
And the greatest flaw with this "simple" talley? Women's eights final: 1 United States 6:05.34 Gold 2 Netherlands 6:07.22 Silver 3 Romania 6:07.25 Bronze Men's quadruple sculls final: 1 Poland ...
An Alternative Olympic Medal Table

james

August 27, 2008
Great discussion and a great "add-on" with the European countries! I still find medals per Capita very interesting because it indicates how many medals a country has won, from the ...
An Alternative Olympic Medal Table

Steve

August 27, 2008
Flawed logic. This comparison would only make sense if the EU could only send the same amount of competitors as a single country. Since it is treated as many small ...
An Alternative Olympic Medal Table

Zeth

August 27, 2008
Hi Benjamin, as far as I know, you can put any GSM SIM card into your OpenMoko, so you have the freedom to choose the best deal for you from ...
OpenMoko vs iPhone - Free your phone or Fight your phone?

Benjamin Melançon

August 25, 2008
Network question. I know more about computers than cell phones. Can anyone tell me or point me to a resource about what purchase options for network access are. For instance ...
OpenMoko vs iPhone - Free your phone or Fight your phone?

Mark (Cycom on freenode)

August 23, 2008
Two separate ideas here: First: Is not the competition between KDE and GNOME a good thing? It drives both to improve in a way that Mac and Windows and Linux ...
Is GUADEC just GDEC?

Zeth

August 21, 2008
Thanks for your comments guys, the newspapers need to sit a while on the naughty step until they are willing to play nicely. John Reese, thanks for visiting, it is ...
Newspapers please link to your sources

John

August 20, 2008
Zeth, The link to this file (for view wireless history) doesn't bring up a dialogue. Could you fix this?
Five Tips for Easter

John Reese

August 20, 2008
They're *carts*, not "trolleys"! ;)
Newspapers please link to your sources

akahn

August 20, 2008
Control-L usually selects the whole address, so only Control-L Control-C would be needed.
Newspapers please link to your sources

Sean

August 20, 2008
That was good. I'm crackin' up.
Newspapers please link to your sources

Garrick

August 20, 2008
Here here!
Newspapers please link to your sources

Seth Kriticos

August 19, 2008
bkil: "GTK and Gecko-tied extensions could be ported to non-gecko browsers." *cough* Epiphany is running on gecko currently and integrates some extensions thereof, they are just planning to switch to ...
Will Epiphany be able to compete with Firefox's extensions?

Harshad Modi

August 18, 2008
Thanks helping me!!! but I have problem on banner.... I try to make my own sftp server using paramiko inherit paramiko.ServerInterface class. but I got this error: ERROR:paramiko.transport:SSHException: Error reading ...
SFTP in Python: Paramiko