An evil equivalent for C expression: 'while x=f()'.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import sys
def set(**kw):
assert len(kw)==1
a = sys._getframe(1)
a.f_locals.update(kw)
return kw.values()[0]
#
# sample
#
A=range(10)
while set(x=A.pop()):
print x
|
This recipe is an abuse of implementation details which should only be used by debugging tools. So I strongly advise you to not use it in production code.
But it's quite fun and can still be useful for bets.
Tags: shortcuts
an alternative using list comprehensions. Again, don't use this in real code.
Very nice.
Alternative, safer methods.
An alternative necessary function definition and example.
But then again.
Better yet. Steven Bethard pointed out in recipe 436482 that
won't work in future versions. In future versions of python - list comprehensions won't expose the inner variable.
Perlishly elegant.
set() is now a builtin. so naming this function "set" is probably not the best idea
Brittle solution. this won't work if you use set() anywhere but the toplevel.
e.g:
-> NameError: global name 'var' is not defined
the behaviour is also different if the loop variable is already bound:
-> equivalent to "while seq.pop(): print 'x'"
Another solution. class DataHolder( object ) : """A simple data holder. """