Top Tips for the Python Programmer
Last week I learnt about using exceptions, which turned out to be the solution to a problem that I’ve mentioned before: if you try to do anything with a variable that hasn’t been initialized, Python throws an exception. In many ways this is good, because trying to do things with non-existent variables can otherwise be a source of hard to find bugs. However, I found it quite annoying when I got exceptions just for checking for a variable and only trying to do things with it inside an if block if it exists. Even the seemingly innocuous statement “if x” will bring a program to a halt if x doesn’t exist.
The way around this is to handle the exception when it occurs, so that the program keeps running but you know that the variable doesn’t exist. For example:
try:
x
except NameError:
#x doesn't exist
else:
#x does exist
This code tries to reference x. If x doesn’t exist, an exception occurs and the code after except is executed (but only if the type of exception thrown matches what’s specified between except and the colon). If x does exist the code after else is executed instead. This is a bit long winded compared to “if x” but it’s better than nothing. Also be aware that different kinds of variables throw different kinds of exceptions when they don’t exist.
- NameError - any single instance of a built in type or custom object, or a sequence where the sequence itself doesn’t exist, eg x
- IndexError - numerical index of a sequence where the sequence exists but the specified element doesn’t, eg x[5]
- KeyError - index of a map where the map exists but an element with that index doesn’t, eg x['y']
- AttributeError - attribute of an object where the object exists but the specified attribute doesn’t eg x.y (often occurs with objects representing XML elements as it can be difficult to predict what child elements they contain)

Comment by Ben Brumfield — 3:58 pm, 3 March 2008 [permanent link to this comment]
Doesn’t Python have anything akin to the
defined?operator in Ruby?Also, under what circumstances are you running into this problem? Usually this kind of thing only comes up when meta-programming.
Comment by Gavin Robinson — 4:50 pm, 3 March 2008 [permanent link to this comment]
As far as I can tell Python has nothing like
defined. Thehasattr()function is useful for finding if an object has the specified attribute but there doesn’t seem to be an equivalent for any of the other exceptions.Where I’m running into problems is with getting XML attributes. I’m using minidom to parse XML files. Each XML element is represented by a Python object. The XML attributes are in a map where the attribute name is the key. I want to know if an element has a certain attribute: it might, but it doesn’t have to. For example if a value is stated in the manuscript it goes in the content of the XML tag, but if the value is uncertain the tag has min and max attributes.
So this code would throw an exception if the element doesn’t have a min attribute:
if element.attributes['min']:
#do something with the value of min
I can use
if len(element.attributes) == 0:to see if it has no attributes, but what if it has some attributes but not the ones I’m interested in?
I wouldn’t be surprised if there was an easier way to do this that I don’t know about, but so far the exception thing is working.
Comment by James Vasile — 3:58 pm, 9 November 2008 [permanent link to this comment]
I believe this code does what you want with less fuss:
if 'min' in element.attributes and element.attributes['min']:Comment by Daniel Cousineau — 12:32 am, 19 November 2008 [permanent link to this comment]
Thanks!
It’d be nice to have even something like the isset() function PHP has… or add a function to the core list API to the extent of .has_key(). Dictionaries have a .has_key()…