Python Pseudo-Switch

Jason Mobarak jason.mobarak at gmail.com
Mon May 9 03:46:44 EDT 2005


# -*- python -*-

import sys


def switchFor (target):
    sw = '__switch_table__'
    # please pretend the frame hack is not here,
    # it happens to work for classes and messing with
    # frame stack in a try/except is probably okay
    try:
        raise Exception()
    except:
        defs = sys.exc_info()[2].tb_frame.f_back.f_locals
    if sw not in defs:
        defs[sw] = {}
    table = defs[sw]
    def _(meth):
        table[target] = meth
        return meth
    return _


class SwitchMixin (object):

    def __init__ (self):
        self.__switch_table__ = self.__switch_table__.copy()

    def switchOn (self, target, *args, **kw):
        return self.__switch_table__[target](self, *args, **kw)


if __name__ == '__main__':

    class SwitchTest(SwitchMixin):

        @switchFor("foo")
        def switch (self, arg):
            print arg * 3

        @switchFor("bar")
        def switch (self, arg):
            print "__%s__" % (arg,)

        @switchFor("baz")
        def switch (self, arg):
            print arg + ''.join(reversed(arg))

    st = SwitchTest()

    st.switchOn("foo", "oof")
    st.switchOn("bar", "rab")
    st.switchOn("baz", "zab")




More information about the Python-list mailing list