This started with a simple question: "is it possible to call isset($foo) in python like in php?" This is probably going about it ass-backwards, or at least it's asking
the wrong question. But then genius of this magnitude doesn't arise from asking the right question.
In the end, I had an answer to my question. I had, perhaps, the stupidest
stupid lambda trick ever. And I had a loving pythonic tribute to
xkcd (for a loving xkcd tribute to python,
click here):
#!/usr/bin/python
"""
a pythonic tribute to xkcd
http://phosphorusandlime.blogspot.com/2008/06/pythonic-tribute-to-xkcd.html
"""
xkcd = lambda x,k,c,d: (({k:False},c,d,c)[int(''.join([str(int(k in i)) for i in [d,c]]),2)])[k] or x
X = 'webcomic'
K = 'romance'
C = {'romance': 'at last!', 'sarcasm':'grep -R soulmate /'}
D = {'math':complex(6,9j), 'language':'to be or not to be'}
print xkcd(X,'language',C,D)
print xkcd(X,'math',{'math':1+1},D)
print xkcd(X,'microsoft',C,D)
print xkcd(X,K,C,D)
# Alternate version
xkcd = lambda x,k,c,d: c.get(k,d.get(k,x))
print xkcd(X,'language',C,D)
print xkcd(X,'math',{'math':1+1},D)
print xkcd(X,'microsoft',C,D)
print xkcd(X,K,C,D)
There are a couple moments of sheer pythonic bliss in there if you pay attention.
Still haven't figured out what it does? Here's a hint:
<?php print $x = ( isset($C[$k]) ) ? $C[$k] : ( isset($D[$k]) ? $D[$k] : $x); ?>
update: added extra c for case where both dicts contain key as pointed out
here and added test case
Labels: stupid python tricks