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

Zeth

November 29, 2009
Hi Jordan, yes that URL is gone now. I have a new contact form on this site.
Python CGI contact forms

Jordan

November 29, 2009
Zeth attention! Your form, http://zeth.me.uk/contact/, is not working The explorer says connecting ..but nothing happens Sorry for my poor English: I am Spanish Regards
Python CGI contact forms

Jordan

November 26, 2009
Sorry: tell me , not tellme (I'm spaniard) And http://zeth.me.uk/contact/ don't work
You got the touch, you got the power

David Jones

November 25, 2009
Your mad skillz are too l33t! for me. I specifically switched to Google Reader so that I could show people what blogs I read. But I couldn't work out how ...
How to find the fashionable blogs quickly

Brian R. Hickey

November 20, 2009
Symantec picked it up too.
How to bring down Internet Explorer with six words

Zeth

November 17, 2009
Thanks djm, I am the moose here. Christian, assuming one actually does Internationalise the countries, it should still work I guess, as the gettext stuff will happen before the list ...
Countries in Django

Phillip Temple

November 17, 2009
Good start, but: a) wouldn't I want None back rather than 'ZZ'? b) why not add a 'shortcut' boolean, then prepend flagged fields (plus usual '-----' separator) to the actual ...
Countries in Django

djm

November 17, 2009
Am I being a moose or did you mean: from whatever.countries import CountryField instead of from whatever.countries import CharField ? Good post though, cheers.
Countries in Django

Christian Joergensen

November 17, 2009
Wouldn't the ordering get messed up after i18n?
Countries in Django

Steve - Electronic Cigarettes Fan

November 17, 2009
Very well done. Is your blog just you writing? Nicely done, Steven.
Blogger vs Wordpress

vetetix

November 15, 2009
Sorry to bother you nearly two years after you wrote this blog article, but I can't manage to find how to modify an existing field. I am trying to change ...
Three Useful Python Bindings - ClamAV, Apt and Evolution

Manju

November 4, 2009
I am transferring some files using psftp to other device's FAT partition. But the filestamp of the file being transferred is modified to that of FAT device, after the transfer. ...
PuTTY Series: Using PSFTP

iki

November 2, 2009
or simpler: socket.gethostbyname_ex(socket.gethostname())[2]
How to find out your IP address in Python

iki

November 2, 2009
local_ip = set([ i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None) if i[0] == 2 ])
How to find out your IP address in Python

Fred

November 2, 2009
testing rst ------------- - point 1
An Introduction to ReStructuredText

Ano

October 27, 2009
"You simply found the license of the StumbleUpon Toolbar for Internet Explorer." That's possible. I've got some more interesting information to add. Firstly, go to this page: https://addons.mozilla.org/en-US/firefox/addon/138 - this ...
Are your Firefox extensions proprietary software?

Ken

October 21, 2009
Stumbled in here at lunch. This is the best find of the week. Thanks.
Three classic command line tips

Jim

October 19, 2009
Thanks for the rtsp:// post - that's something that has been bugging me for a while!
Three classic command line tips

Zeth

October 18, 2009
Thanks for the comments guys. Great to see the all the gang are still here!
Three classic command line tips

Bubba

October 18, 2009
Is there any way psftp can return the true transfer rates oberved during the actual transfer?
PuTTY Series: Using PSFTP