[Python-ideas] Where-statement (Proposal for function expressions)

Mike Meyer mwm-keyword-python.b4bdba at mired.org
Sun Jul 19 06:56:37 CEST 2009


I wrote this, then pretty much rejected this due to the "upside-down"
nature of where, but the BDFL said he sort of liked it, except for the
name - and that we should be shaking out 3.X instead of extending the
language. So, just to get it on record, how about a B&D version of the
where statement? Let's call it the "with" clause. The grammar
extension (based on the 2.6 grammer) would be:

stmt_with_with: small_stmt 'with' name_list':' bind_suite
bind_suite = bind_stmt | NEWLINE INDENT bind_stmt+ DEDENT
bind_stmt = expr_stmt | funcdef | classdef
name_list = NAME (',' NAME)*

The semantics look like this (modulo the non-hygenic nature of the
macro conversion):

old_locals = locals()
old_names = set(old_locals)
bind_suite
new_names = old_names.union(name_list)
for key in locals:
    if key not in new_names:
        del key
small_stmt
for key in name_list:
    if key in old_locals:
        eval '%s = %s' % (key, old_locals[key])
    else:
	del key

The bind_suite is effectively run in a new scope, as the current scope
won't be affected by any bindings in it. In particular, global and
friends can't be used in bind_suite. The statement that the with
clause is attached to is then executed in the enclosing scope - as
that's where any bindings will happen, with the variables in
name_list, and no others, added to it. After that, we restore the
existence/values of the variables in name_list to their old
value. Yes, this means if you do something like:

x = a + b with x, a, b:
    a = 2
    b = 3

then the value of x is going to get lost afterwards. That's a bug in
your code.

     <mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.

O< ascii ribbon campaign - stop html mail - www.asciiribbon.org



More information about the Python-ideas mailing list