473,387 Members | 1,864 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Python Pseudo-Switch

Hello All,

Because of my poorly designing a database, I have recently found it necessary
to explore the wonders of the Python pseudo-switch:

do_case = { "A" : lambda x: x["bob"],
"B" : lambda x: x["carol"],
"C" : lambda x: "Ted",
"D" : lambda x: do_something(x) }

my_thing = do_case[get_value_from_thin_air()](adict)
How to handle this kind of thing when lambda is removed from the language,
beside the obvious def'ing those tiny little functions?

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 19 '05 #1
3 1825
James Stroud wrote:
Hello All,

Because of my poorly designing a database, I have recently found it necessary to explore the wonders of the Python pseudo-switch:

do_case = { "A" : lambda x: x["bob"],
"B" : lambda x: x["carol"],
"C" : lambda x: "Ted",
"D" : lambda x: do_something(x) }

my_thing = do_case[get_value_from_thin_air()](adict)
How to handle this kind of thing when lambda is removed from the language, beside the obvious def'ing those tiny little functions?


You can always re-invent lambda.
def lambda2(arg_names, expression): .... exec 'def _(%s): return %s' % (','.join(arg_names), expression)
.... return _
.... add = lambda2(('x', 'y'), 'x + y')
add(3, 4)

7

Jul 19 '05 #2
James Stroud wrote:
Hello All,

Because of my poorly designing a database, I have recently found it necessary to explore the wonders of the Python pseudo-switch:

do_case = { "A" : lambda x: x["bob"],
"B" : lambda x: x["carol"],
"C" : lambda x: "Ted",
"D" : lambda x: do_something(x) }

class CaseThing:
def pref_A (self, x):
return x["bob"]
def pref_B (self, x):
return x["carol"]
def pref_C (self, x);
return "Ted"
def pref_D (self, x)
return do_something(x)
def getThing (self, x):
attr = getattr(self, 'pref_%s' % (x,))
if attr is not None:
return attr
else:
raise SomeError("Thing %s does not exist" % (x,))

my_thing = CaseThing().getThing(get_value_from_thin_air)(adic t)

You can do something similar with method decorators for more complex
strings than what's allowed for python method names.
my_thing = do_case[get_value_from_thin_air()](adict)
How to handle this kind of thing when lambda is removed from the language, beside the obvious def'ing those tiny little functions?

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/


Jul 19 '05 #3
# -*- 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")

Jul 19 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Bo Peng | last post by:
Dear Python group: I am planning on an application that involves several complicated C++ classes. Basically, there will be one or two big data objects and some "action" objects that can act on...
37
by: seberino | last post by:
I've been reading the beloved Paul Graham's "Hackers and Painters". He claims he developed a web app at light speed using Lisp and lots of macros. It got me curious if Lisp is inherently faster...
3
by: Maurice LING | last post by:
Hi, I am wondering if Python has services or frameworks that does the same as Java RMI? What I am seeking is to do "pseudo-clustering". That is, a server will contains a program to control...
12
by: Tolga | last post by:
Hi everyone, I am using Common Lisp for a while and nowadays I've heard so much about Python that finally I've decided to give it a try becuase Python is not very far away from Lisp family. I...
24
by: Mark | last post by:
Hi, I'm new to python and looking for a better idiom to use for the manner I have been organising my python scripts. I've googled all over the place about this but found absolutely nothing. I'm...
53
by: Vicent Giner | last post by:
Hello. I am new to Python. It seems a very interesting language to me. Its simplicity is very attractive. However, it is usually said that Python is not a compiled but interpreted programming...
13
by: John Dann | last post by:
A Python newbie, but some basic understanding of how classes, objects etc work in eg VB.Net. However, I'm struggling a little to translate this knowledge into the Python context. I'm trying to...
13
by: iu2 | last post by:
Hi, This is a little bit strange post, but I'm curious... I learned Python from its tutorial step by step, and practicing writing small scripts. I haven't seen a Python program before knowing...
0
by: Tyler Breisacher | last post by:
To paraphrase this video (http://www.youtube.com/watch?v=zJOS0sV2a24) (which is the Randall Munroe, author of the famous xkcd (http://www.xkcd.com/), giving a talk at Google), "you just type the...
30
by: Ivan Reborin | last post by:
Hello everyone, I was wondering if anyone here has a moment of time to help me with 2 things that have been bugging me. 1. Multi dimensional arrays - how do you load them in python For...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.