[Python-ideas] if with as

Josiah Carlson jcarlson at uci.edu
Wed Mar 7 22:43:17 CET 2007

Sam <free.condiments at gmail.com> wrote:
> On 04/03/07, Scott Dial <scott+python-ideas at scottdial.com> wrote:
> > As for this particular case, it is only useful in a very restricted set
> > of expressions and I was only able to find a handful of cases in stdlib
> > where I could drop in a "if x as y". I believe this is an indication of
> > how rarely one wants to do this. YMMV.
> I do think that the majority of use cases will be parsing, or in
> similar cases where one needs to both test for success and obtain
> results from the test.

I'm going to agree with Scott Dial on this.  You aren't going to need it
often enough to warrant this syntax change.  Coupled with the potential
confusion that Jim Jewett pointed out, and this particular suggestion
smells like a misfeature.

Also, with the nonlocal declaration that is going to be making it into
Python 3 (or was it 2.6?), you can use a closure without a list to do
the same thing.

    def foo():
        result = None
        def do_something(...):
            nonlocal result
            result = 8
            return True
        if do_something(...):
            #do something with result

Then again, closures, assignments in while/if, etc., all smell to me
like a way of getting the features of object semantics, without actually
using objects.  Take your final example and use an object instead.

def targetDistributor(actor, rest, info):
    matcher = Matcher()

    if matcher.match(target_set_pattern, rest):
        name, target = matcher.result
        targetSet(actor, name, target)
    elif matcher.match(target_clear_pattern, rest):
        name, = matcher.result
        targetClear(actor, name)
    elif matcher.match(target_list_pattern, rest):

You know what?  That works *today* AND is clearer and more concise than
your original code.  Even better, it doesn't require a language syntax

Try using an object for this.  You may find that it can do everything
that the assignment thing could do.

 - Josiah

More information about the Python-ideas mailing list