The Second Order Effect

Replacing twisted if/else statements in Python…

by on Nov.24, 2009, under Tech Articles

I’ve been having a growing love affair with Python for over a year, thumb and now that I’ve got a few projects that I’m working on – I’m using Python as my primary language.

I had a happy moment when refactoring a section of annoying if/then/else sections …

if object.type == "Vendor1":
foo = Vendor1()
elif object.type == "Vendor2":
foo = Vendor2()
elif object.type == "Vendor3":
foo = Vendor3()
else:
raise Exception("Not a handled type")

Python is a functional language, thumb and this means (among other things) that functions, generic classes, and all sorts of stuff can exist in dictionaries. So, instead, I can do

lookup = { "Vendor1" => Vendor1, "Vendor2" => Vendor2, "Vendor3" => Vendor3}
try:
foo = lookup[object.type]()
except KeyError:
raise Exception("Not a handled type")

It’s not a big thing, but it made me happy — and the example can be extended …

lookup = {
"Vendor1" => { "url" => blah, "threads" =>"blah", "obj" => Vendor1() }
}
 
lookup["Vendor1"]["url"]
#equals blah

Today, it’s all about the little things.


5 Comments for this entry

  • Ian

    Nice. In PHP I would solve it with the eval() function:

    $lookup = array(‘Vendor1′ => ‘Vendor1′, ‘Vendor2′ => ‘Vendor2′, ‘Vendor3′ => ‘Vendor3′);

    $foo = in_array($object_type, $lookup) ? eval($lookup[$object_type]) : false;

  • Rizwan Kassim

    Yeah, fair pait. Eval’s dangerous though — given it’s dangerous, would you actually do it that way, or do you if/then/else?

    Python’s culture is very much about clean and elegant code – I do love that I stop and think of the quality of my code a lot more when writing Python, because there’s the culture of Pythonic code… And, of course, import this.

  • Ian

    If you’re actually doing it as indicated – i.e., pulling your function names from an array, as opposed to from user input or the database – I don’t see why it’s any more dangerous than your method.

    I do need to learn Python though. However, due to the needs of my job, it’s lower on my list than Flash.

  • Rizwan Kassim

    yeah, I’d do Flash first too, given your work. But Python makes me giddy and happy to code again – it’s been a while since I’ve had that.

  • Harry

    What Have The Romans Ever Done For Us, Eh ? ? ?

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...