New syntax for blocks
steve
steve at lonetwin.net
Wed Nov 11 08:10:03 EST 2009
Hi,
On 11/11/2009 12:30 PM, r wrote:
> [...snip...]
> I think what has escaped everyone (including myself until my second
> post) is the fact that what really needs to happen is for variable
> *assignments* to return a boolean to any "statements" that evaluate
> the assignment -- like in an "if" or "elif" construct. The current
> "with" statement cannot replace that action and was never meant for
> such things.
>
True. It escaped me too that the assignment was happening and I was only relying
on the side-effect to break out of the with statement. So, I'm sorry.
>
> Very clean, very elegant solution to a messy problem that pops up in
> python code quite often. It not only saves one distracting line of
> code per usage but makes the code more readable. If there is an
> existing solution, Steve's is not it.
However, if it is /only/ about saving that one 'distracting' line of the final
code that you are concerned about (which I think is the case), how about:
-----------------------------------------------------
def deco(f):
def assign(x):
if x:
globals()['value'] = f(x)
return True
else:
globals()['value'] = False
return assign
@deco
def something_that_returns_value(x):
# do something with x and return a value
return x
if something_that_returns_value(1) and value:
print value
if something_that_returns_value(0) and value:
print value
# or if you cannot decorate something_that_returns_value in it's definition
# for instance, a method from another module, then ...
if deco(something_that_returns_value)(0) and value:
print value
# Note that we've just siphoned off the assignment elsewhere. One problem
# tho' is, irrespective of the conditional code being entered 'value' would
# be initialized, which is what your ...
#
# if something_that_returns_value(x) as value:
#
# ... would also have done (if such a thing existed).
# To avoid this side effect we could also do:
if (something_that_returns_value(0) and value) or globals().pop('value'):
print value
# ...but that is beginning to look too much like the perl.
Well, that's all i could think of to overcome one line of extra code.
cheers,
- steve
--
random non tech spiel: http://lonetwin.blogspot.com/
tech randomness: http://lonehacks.blogspot.com/
what i'm stumbling into: http://lonetwin.stumbleupon.com/
More information about the Python-list
mailing list