This post originated from an RSS feed registered with Python Buzz
by Ben Last.
Original Post: Always In The Last Place You Look
Feed Title: The Law Of Unintended Consequences
Feed URL: http://benlast.livejournal.com/data/rss
Feed Description: The Law Of Unintended Consequences
Every so often, some little Python feature reminds me of why I like this language. For divers sundry reasons, I need a one-line way to
Test if an object has an attribute
If so return the value of it
If not return a default
One line, remember, so no try: allowed. (hasattr(object,'attribute') and object.attribute) or default
Holy run-time binding, Batman... I know, it's trivial and obvious, but little things like this give me pleasure.
Which brings me, circuitously as ever, to something else. I'd like to share a revelation I've had during my time here[1], concerning the subtle art and exact science[1] of debugging.
Yesterday, I entered one of those cycles familiar to all developers; the Persistent Error Cycle. I hit F5 to refresh the web page, which is being served up from my Zope site. Instead of the pleasantly designed and intelligently programmed result I expect, I get a terse Zope-esque notification of a Python exception. The name argument is giving me an AttributeError. Cool and poised, I alt-tab my way to the editor, where the cursor sits on the line that contains (amongst many other things), the path environment/argument. And so it starts. No matter what I do to that line, the error persists. I change it to a python: call. Nothing. I put in a hasattr() check. Nada. I remove any mention of argument, ruthlessly expunging any sign that it had ever existed, consigning it to the Memory Hole of the undo stack. Zippo. Of course, you're way ahead of me here; the offending reference was a page or so further down the file. I had made assumptions about the error, not seen it as it was, but seen it as I believed it to be.
This got me thinking, as the web testing started to pound the site with a simulated frenzy as of a hundred thousand frantic punters begging to buy, about expectations, and reminded me of their power. Perhaps it also had something to do with the impressive yet balding Mr Derren Brown, whom I much admire; his act relies on setting and manipulating people's expectatons. By the way, did you notice that the last word of that sentence was mispelled? And the last word of that one also. Anyway, all too often I've found that an apparently intractable bug is something perfectly simple that I'm not really seeing properly. Often, all I need is to get up from the chair, go and make a cup of tea and take a couple of minutes away from it. When I return, the problem as it is lies in front of me, my preconceived ideas of it have gone.
So, my decidedly British conclusion is; at the first sign of a stack trace, put the kettle on. You'll probably need it.