dynamic class/module use? (like Java's forName)

Terry Reedy tjreedy at udel.edu
Sun Jul 18 05:21:59 CEST 2004


"Alex Hunsley" <lard at tardis.ed.ac.molar.uk> wrote in message
news:8glKc.31979$v7.20488 at fe2.news.blueyonder.co.uk...
>
>   if (actionString == "blah"):
>       blahThang = blah(constructor stuff)
>       blahThang.doSomething()
>   else if (actionString == "blah2"):
>       blahThang2 = blah2(constructor stuff)
>       blahThang2.doSomething()
>   else if (actionString == "blah3"):
>       blahThang3 = blah3(constructor stuff)
>       blahThang3.doSomething()
>   else if (actionString == "blah2"):
>    # etc etc

The Python idiom for something like the above is to use a dict instead of
if/else.
It is especially useful when you want to add alternatives at runtime.
Something like

actions = { 'blah':blah, 'blah2', blah2, 'blah3':blah3, ...}
# easily extended at runtime
...
actions[actionString](constructor_stuff).doSomething

Terry J. Reedy








More information about the Python-list mailing list