New syntax for blocks
steve
steve at lonetwin.net
Tue Nov 10 15:49:03 EST 2009
Hi,
On 11/11/2009 12:53 AM, r wrote:
> Forgive me if i don't properly explain the problem but i think the
> following syntax would be quite beneficial to replace some redundant
> "if's" in python code.
>
> if something_that_returns_value() as value:
> #do something with value
>
> # Which can replace the following syntactical construct...
>
> value = something_that_returns_value()
> if value:
> #do something with value
>
> i dunno, just seems to make good sense. You save one line of code but
> more importantly one indention level. However i have no idea how much
> trouble the implementation would be?
I guess the problem would be that this would go against the (design ?) principle
of not evaluating functions in the 'if' conditional part, because it would lead
to statements such as:
if something(someother(sumsuch() + thisthing())) + ... == value:
also, assignment in the 'if' statement was consciously avoided, if I am not
mistaken.
However, the same 'effect' can be obtained with the 'with' statement:
------------------------------------------------
class something_that_returns_value:
def __init__(self, x):
# do something with x, self.value is what ought to be 'returned'
self.value = x
def __enter__(self):
if self.value:
return self.value
else:
return ValueError()
def __exit__(self, type, value, traceback):
return True
with something_that_returns_value(1) as value:
print value
with something_that_returns_value(0) as value:
print value
with something_that_returns_value(False) as value:
value + 10
# never reach here
value.dosomething()
with something_that_returns_value([1,2,3]) as value:
value.append(4)
print value
------------------------------------------------
nasty huh ? :)
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