Wednesday, August 27, 2008

Wakeup, Facepalm, Yield, repeat...

Today I dove into threading in Python for the first time. Usually the best way to learn is by experimenting, so, I decided to write a small test program. To begin, I started with what I thought would be the absolute minimal "threading" program, a single threaded program that just imports the "threading" module. Not useful, but, lets just do a sanity check.


import threading
print "hi"


To my utter amazement, I get back


hi
hi


Good thing I did this sanity check? Something is going on here I don't understand.

So, I start probing. I flush stdout before importing threading-- it still prints twice.

I import time and sleep for a second before importing threading-- it still prints twice.

It gets worse. I fire up an interpreter and try to import threading and... wait for it... I still get 'hi'. WTF?!?


Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import threading
hi
>>>


It takes me a few minutes after seeing this, but I finally get it.

My test file was named "threading.py". D'oh!. I was importing myself, hence, the duplicate "hi"s. A simple but painful lesson in avoiding module name collisions.