Monday, February 20, 2006

Python wish: a new meaning for "import ... as ..."

For Python modules that are meant to be imported, I usually try to put the testing code inside the module using the standard

if __name__ == "__main__":

block of code.

However, if the module is also meant to possibly be used by itself, then this approach doesn't work and the testing code has to be put in a separate module. I wish it would be possible to write something like

if __name__ == ''

inside and that importing the module using

this_module as SomeNameChosenForTestingPurpose

would result in the variable __name__ inside being assigned to SomeNameChosenForTestingPurpose. This would allow the inclusion of the testing code to be always kept inside a given Python module. To build a test suite, one would only need to have a module that does a series of "import ... as ..." statements.

As it is, __name__ is either equal to "__main__" or the original name of the Python file (this_module in the example above).

===In short, I would like to be able to design Python modules in this way:

some clever Python code

if __name__ == "__main__":
some clever Python code to be
executed when this module
is called as the main program.

if __name__ == "SomeNameChosenForTestingPurpose":
Some clever Python code
to be executed when
this module is imported as

Sunday, February 12, 2006

Was rur-ple broken for Linux?

A while ago, I made some changes with the help of a MacOS user so that rur-ple could work properly with that platform. Since then, many people downloaded it; I assumed that everything was working properly as there was no bug report - until tonight. Under Windows, if you start rur-ple by double-clicking (which is what I always do), everything is ok. However, if you start it [version 0.9.5] with "python", nothing happens! I assume that this is the way it is invoked by Linux users too... I just made a small change which should make it work. The new version on sourceforge is 0.9.5a. If there are any users out there who could report if it works properly (and under what operating system), I would be most grateful!

Lightning 1.7 released

As requested by a user, I've added the possibility to pass arguments to a running script. The arguments are passed as a string (named _Args). The new version is available from the usual place.

One thing I have noticed is that scripts that contain encoding information give a run-time error. It is thus necessary to remove the encoding information (a line like # -*- encoding: latin-1 -*-) prior to running the script. If anyone knows of a different workaround, I'd appreciate hearing about it.

Lightning 1.6 released

Following some suggestions left by readers on the previous post of this blog, Lightning 1.6 has been released. The main visible change is the possibility to change the layout and have the output window "switched" from the bottom of the editor window to the right of the editor window (and vice versa).

The code has also been refactored so that it should be possible to customize various display options (default window sizes and fonts primarily) without having to understand how the rest of the program is structured.

Planned for the next release is the ability to simulate running a program with an argument list.

Saturday, February 11, 2006

Lightning compiler: drag and drop option

A new version (1.5) of Lightning Compiler has been released. It is now possible to "drag" a file (icon) and "drop" it in the editor window. The text of the file will be automatically imported to the editor window. This option has been added following a suggestion. Since I believe that it fitted well with the philosophy of L.C. as a quick-and-painless testing tool for Python scripts, I decided to implement it (which was surprisingly easy, thanks to wxPython!)

Feel free to suggest other useful options. :-)

Wednesday, February 08, 2006

A question of design (Lightning 1.4)

Since the release of my little app, Lightning Compiler :-), I have been confronted with design issues that, I imagine, many of those reading this blog face often in the course of their daily work. However, since I only program as a hobby, the issue of ui design is essentially all new to me. Going through the experience for a second time (the first was when I designed rur-ple) has given me a better appreciation of Joel Spolsky writings on the subject.

Lightning Compiler was originally meant as a teaching tool embedded in rur-ple. As such, it was very simple by design. Since I "extracted" it from rur-ple to become a stand-alone tool, I have been faced with the temptation of adding various features (creeping featuritis?), following users' comments (3!), especially when they had themselves made some modifications that they found useful.

I don't want Lightning Compiler to become a bloated app. ;-) Actually, as anybody that has looked at it would know, there is very little danger of this happening anytime soon - at least, by the usual understanding of what a bloated app is. Still, I want to keep it simple and true to its orginal purpose. I would be very interested in hearing about other programmers' comments on my thoughts on the issue of design of an app like Lightning Compiler (L.C. for short), especially given my relative lack of experience on the subject. To provide a starting point to the discussion, here are a few thoughts on the subject.

  • L.C. is meant as a "quick and dirty" little app, useful to test some programs, usually short ones but that would be too long to type (and re-type) at the interpreter prompt. The idea is: type a program, press a button to execute, look at the output; make some changes and repeat the process.
  • L.C. is meant to add a "nice" user interface for input() and raw_input() commands when needed. This is its one "unique" feature as far as I know.
  • L.C. can also be use to run (and modify, and run again...) longer programs obtained from elsewhere - like, for instance, the Python Cookbook. The idea is to be able to cut-and-paste a code sample and run it with as little fuss as possible.
  • L.C. should be as simple as possible to be useful to do this - but no simpler.
With these objectives in mind, here are some of the design features with the motivation for each of them:
  • L.C. is a gui app that is meant to be lauched either from a terminal window or (under Windows XP, which I use - sorry to Linux and Mac users;-) by double-clicking on it. Still, I keep a terminal window present so that error messages from running L.C. itself can be read and captured. (This was especially useful in the original writing of L.C.)
  • L.C has two basic windows: an editor window and an output window; print and error statements are redirected to the output window when running a program (and redirected back to the default terminal window afterwards, so that error messages from running L.C. are captured separately).
  • L.C. has no menus, only buttons. Each option/operation is thus meant to be always visible at all time. Since nothing is hidden, the number of options has to be small ;-)
  • L.C.'s buttons are simple labeled buttons (no fancy image); the idea is to keep it in a single file, as small as possible.
  • Button labels are only in English. Well, this is of course easily changed by an individual programmer; this is a programmer's tool after all.
  • Each action that can be performed by pressing a button can also be performed by a key combination. This is to allow "power users" to use it without their hands leaving the keyboard. From what I have read, this is considered nearly essential by *nix power users ;-)
  • Possibility to hide the output window, giving more space to the editing window (to see more code at once); when hiding the output window, the amount of screen-space it occupies (after possible adjustment by the user) is remembered.
  • Focus in the editor window at the start; ready to type and run :-)
  • Default size of output window just large enough that all "help text" can be displayed at once in it... but no longer.
  • Access to the interpreter, through a tabbed interface. This should be especially useful for finding information about modules with dir() or help()
  • (New) If some text is selected, only that text is executed - but a warning is added in the output window ... especially in case the selected text is not visible in the Editor window because of scrolling...
  • (New) Go to line number feature; should be useful when an error message is seen in the output window.
  • The text from the output window is NOT cleared each time a new program execution (run) occurs; I know that one user changed that default so that his output window is cleared each time. My reasoning is that a user should be able to run the program, change a parameter, run it again, and be able to compare the results of each run. It is easy enough to clear the output after all (ctrl-l or pressing a button).
  • No "find" feature. I've debated about this one... I looked at the wxPython demo and realised that, to do this properly requires more than a few lines of code... Furthermore, if one runs a program and gets an error message, only the line number (with the new "go to" feature) is really needed. I'm still debating...
  • NO find-and-replace feature. This is something that is useful in a full-fledge editor or IDE, but seems to be an overkill for an app of this kind.
  • Open and save file; this should be self-explanatory. No "save as"; can be easily done within save - actually "save" is really a "save as". ;-)
  • Help button; just as a reminder that it is available.
  • L.C. has no provisions for running programs that expect some arguments. I believe that if this can not be simulated with an added "if __name__ == '__main__" block, then you should use a different tool to work with.
That's it. What are your thoughts? Is there anything that I should have done differently?

Tuesday, February 07, 2006

Lightning 1.3: yet, one more!

I was reading a post on comp.lang.python and thought:
Wouldn't it be nice to see to try to import this module and use dir() and help() to find out ...
Then I realised that it would be silly to use Lightning Compiler :-) to do so; this was clearly a task better left for the interpreter. Then it dawned on me...

Version 1.3 is out. I changed the layout to use a wxNotebook, with the first page being the same Python Editor as before, and the second page is an embedded Python Interpreter, for those rare occasions when you just need it. All this, under 20kb (of course, using wxPython to do the heavy work), and it still loads in less than a second on my computer.

Of course, for the really heavy work, I still use SPE...

P.S. Remember that the Editor handles input() and raw_input() much better than the Interpreter does! ;-)

Lightning 1.2: yet, another new version!

Inspired by a comment left on my last post, I made yet another change to Lightning Compiler :-) The output window is now at the bottom, so that longer lines can be easily seen both in the editor window and the output window. The reason I didn't do it like this in the first place was that I found that too little text showed up in the editor window by default. However... the new version has an option to hide the output window (using a button, or directly from the keyboard).

Feel free to make more suggestions! As long as it doesn't bloat the program, and that I see some use for them... I'll make the changes to this toy app.

Now, for something somewhat unrelated... I had posted a simplified version on the online Python Cookbook. Now, because of new additions, it no longer longer appears on the front page, and will probably never be commented on again. [After all, who would think of looking for such a little app in the Python Cookbook.] But, just for fun, if you find Lightning Compiler useful, why don't you go to the online Python Cookbook and give it a rating. It would be kind of fun if it turned out to be the most often rated recipe ;-)

Monday, February 06, 2006

lightning 1.1: new and improved

Non North-American readers: You may want to skip the "Infomercial" as it probably is something unique to our continent...
Are you tired of retyping some complicated indented code at the interpreter prompt?

Do you get annoyed with mixed tabs and spaces?

Do you find it troublesome having to start a full-fledge IDE just to test a few lines of code?

With Lightning Compiler, you don't have to!

Lightning Compiler allows you to open files and save them, or simply type in your Python code from scratch just like a more expensive editor. However, unlike these complicated programs, Lightning Compiler also allows you to test your code instantly, at the click of a button.

The new and improved Lightning Compiler even allows you to do all this without even having to use a mouse: you can control it entirely from your keyboard, just like the Unix gurus!

But wait, there's more!

If you download Lightning Compiler right now, we'll throw in a source colorizer in the editing window absolutely free. With the source colorizer, you will never make a typo in a Python keyword as you edit your code. In addition, we'll include a tab-to-4 space automatic conversion.

And that's not all... Lightning Compiler runs on all major platforms.

So, what are you waiting for? You can download Lightning Compiler right now!

Mirrors are standing by!

Lightning compiler is provided as is, with no guarantee. Possible side-effects include: carpal tunnel syndrome, cross eyes, sore neck, and general lack of social life. Python (and its batteries) and wxPython not included.
======End of Infomercial=====

I always wanted to do a fake infomercial... Now that it's done...

In the past week, I was looking at the stats on download for rur-ple, following the latest release of the lessons and of rur-ple itself, and noticed a fairly large increase. I felt good about that, given all the time I spent on it. Then, I noticed that I could look at individual stats for all the "packages". Much to my surprise, "Lightning Compiler" was responsible for a significant part of the increase in downloads. Not bad for just a little app that was extracted from rur-ple! I even got just about as much feedback (two comments in a week!) on it than I got for rur-ple in about a year. When I first released it, I gave it a version number 1.0, even though it was not very polished. I thought I was done with it as it was answering my needs as a small one-purpose tool. However, as a result of the comments I got, I made some changes to Lightning Compiler, and produced a version 1.1!

For those that don't know about Lightning Compiler, it is a simple windowed app: one window is a Python editor, the other an output window. Your can run your code, and watch the result in the output window, with input() and raw_input() handled through dialogs (wxPython based).

It is not meant to be a "serious" app, but I find I use it more and more, and almost never use the Python interpreter anymore!

Friday, February 03, 2006

Fixing Reeborg: introducing classes

For those familiar with rur-ple lessons, I thought I would share the first draft of my introduction to classes. Some points to remember from preceding lessons:
  • I used the analogy of synonyms to talk about variables
  • Students have already seen how to define new object [like Reeborg = UsedRobot()]
I definitely welcome comments!

Fixing up Reeborg

As we have seen, we can create new robots by using the notation

Reeborg = UsedRobot()
Erdna = UsedRobot(2, 2)

However, these robots are just like the original nameless one: they
can only turn left. To teach them how to turn right, we could define
a function similar to what we did before:

def Reeborg_turn_right():
for i in range(3):

However, there are at least two problems with this approach:

  • We need to define a similar function for every single robot we create (Reeborg, Erdna, ...).

  • Reeborg and turn are separated by an underscore character "_" for the function we defined [to turn right] and by a dot "." for the built-in method [to turn left]. This would not look right...

A better approach is to define a new class that would inherit from the class UsedRobot. This is
what we do in the next section.

Designing a new class

I will show you first how we can fix our robot so that it knows how to turn right, and explain what I did afterwords.

class RepairedRobot(UsedRobot):
def turn_right(synonym_used_to_refer_to_this_object):
for i in range(3):

Here's how we can then use this new class of objects:

newReeborg = RepairedRobot()
newErdna = RepairedRobot(2, 2)

newReeborg.turn_left() # as before
newReeborg.turn_right() # new method!

newErdna.turn_right() # this one works too!

And now, it is time to explain. The Python keyword class indicates that we are going to define a new type of "function", one that creates objects. What follows class is: RepairedRobot(UsedRobot).

RepairedRobot is the name of our new class; by writing UsedRobot between the parentheses, we ensure that the new class RepairedRobot inherits all the methods and attributes that UsedRobot had. Thus, when we write:

newReeborg = RepairedRobot()

we create a new robot "named" newReeborg which can do (at least all) the same things that the old Reeborg = UsedRobot() could do.

Next, inside the new class, as indicated by the indented block, we define a new method, turn_right(). By defining it inside the class, we take the first step to insure that all the robots that are created by calling RepairedRobot() will be able to turn right!

The second step that is required is to tell Python that the method will "belong" to the particular object that has been created. To do so, we use the variable synonym_used_to_refer_to_this_object which will refer to newReeborg, newErdna, etc., depending on what object is created. When we write

newReeborg = RepairedRobot()

Python creates a new instance of the class RepairedRobot and defines all the methods, replacing the first argument of the method (synonym_used_to_refer_to_this_object) by the name of the
instance (newReeborg).

Now, synonym_used_to_refer_to_this_object is rather a long name to type. By convention, another variable name is used: self. Thus, to follow the normal convention, I should have

class RepairedRobot(UsedRobot):
def turn_right(self):
for i in range(3):