Replacing twisted if/else statements in Python…
by Rizwan Kassim on Nov.24, 2009, under Tech Articles
I’ve been having a growing love affair with Python for over a year, 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, and this means (among other things) that functions, 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.
November 24th, 2009 on 7:21 pm
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;
November 25th, 2009 on 11:54 am
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.
November 26th, 2009 on 12:50 am
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.
November 26th, 2009 on 12:46 pm
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.
December 14th, 2009 on 5:03 pm
What Have The Romans Ever Done For Us, Eh ? ? ?