New syntax for blocks

r rt8396 at gmail.com
Wed Nov 11 02:00:09 EST 2009


On Nov 10, 2:49 pm, steve <st... at lonetwin.net> wrote:
(..snip..)
> However, the same 'effect' can be obtained with the 'with' statement:
(..snip..)

Hardly!,Here is an interactive session with your test case
#----------------------------------------------------------#
>>> 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 'block'

block
>>> with something_that_returns_value(0) as value:
      print 'block'

block
>>> with something_that_returns_value(False) as value:
      print 'block'

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

block
#----------------------------------------------------------#

The block obviously executes every time no matter what value is
returned from something_that_returns_value(*). The with statement is
meant to only cleanup an exception in a "nice-clean-way" not to
evaluate a variable assignment as evidenced by this simple testing of
your code. If anything executes in the block following the "if" (when
the assignment value is None) it undermines the whole reason for using
the new syntax in the first place!

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.

if range(0) as var:
   #python will never execute even one line
   #in this block because bool(var) == None
   #also since bool(var) equals None, the
   #variable "var" will never be created!

elif range(10) as var:
   #this block will execute and the variable "var"
   #will be added to appropriate namespace containing
   #a list of 10 ints

var = 100 #var is still available in this namespace!


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.



More information about the Python-list mailing list