TheInitializer TheInitializer - 7 months ago 20
Python Question

Is this a correct place to use exec/eval?

So I keep hearing everyone saying "don't use exec, don't use eval, etc." But I was wondering if it's correct to use under this cirumstance.

I have multiple functions that do the same thing for different operating systems:

def doCoolStuff_Windows():
# do cool stuff here, windows edition

def doCoolStuff_Darwin():
# do cool stuff here, mac edition


Then I have one master function that detects the user's operating system and runs the correct function for it.

I decided instead of doing a giant if-else thing, it would be easier to use exec like this:

def doCoolStuff():
system = platform.system()
exec "doCoolStuff_%s()" % system


Is this a correct usage of exec? Or is there a more correct way to accomplish the same task?

Thanks

Answer

Not trying to start a flame war, but... No, imo that's not really a valid use of exec when there's a really easy alternative and very rarely is there ever a good reason to use eval.

You can simply setup a dispatch dict like so, or just use an if statement which would be simpler here.

 dispatch = {'Windows': doCoolStuff_Windows, 'Darwin': doCoolStuff_Darwin}
 def doCoolStuff():
     system = platform.system()
     if system in dispatch:
         dispatch[system]()