New syntax for blocks

steve steve at
Tue Nov 10 21:49:03 CET 2009


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 

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
              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

with something_that_returns_value([1,2,3]) as value:
      print value

nasty huh ? :)

- steve

random non tech spiel:
tech randomness:
what i'm stumbling into:

More information about the Python-list mailing list