• 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

Tringi

December 1, 2008
Hi, I am far from your league, but instead of [20. Nd5], why not just play Qd8? :-) Wouldn't it be only Qd8 Qd8 then, or am I missing something?
Ruy Lopez, Berlin defence, open variation part three

Tringi

November 30, 2008
...oh, I meant "Qe8 Qe8" in my previous post, sry ;-)
Ruy Lopez, Berlin defence, open variation part three

Cruze

November 29, 2008
Buy discount professional health products online.
Include ODF support in the Linux Standard Base?

Mike

November 29, 2008
>The most useful xmlstarlet tool for me has been the XML validator, >which tests whether your documents are well formed or not. You >use the tool as follows: >xmlstarlet val ...
My God, it's Full of XML

Giacomo

November 29, 2008
Er, "elif test `ls "$with_xqilla"/libxqilla*.so 2>/dev/null | wc -l` -gt 0 ; then" should now be "elif test `ls "$with_xqilla"/libxqilla.so* 2>/dev/null | wc -l` -gt 0 ; then", as the ...
Native XML storage with Berkeley DB XML - part one

Felipe Coury

November 23, 2008
What do I have to say? Only this: "THANK YOU"! Awesome!
SFTP in Python: Really Simple SSH

fmv

November 19, 2008
just a real db SAMPLE please
Native XML storage with Berkeley DB XML - part one

Very helpful

November 12, 2008
but i need more help. I'm have to execute the sudo command after I log in. What do I need to do to enter the password after the sudo command ...
SFTP in Python: Really Simple SSH

blz

November 12, 2008
I buy 99% of PEP8, except: I don't like the line spacing rules... I can't read the code when it's too close together - it looks congested and I can't ...
Twelve commandments for Beautiful Python code

Zeth

November 11, 2008
Hi Ioxs, I said above *"I will give an example of a standard directive, then an example of a third-party directive"*, so the image directive is the example of a ...
An Introduction to ReStructuredText

loxs

November 9, 2008
Hello, Are you sure about the sourcecode directive, because I didn't manage to make it work. And it doesn't work with the online renderers too.
An Introduction to ReStructuredText