[Python-ideas] Anonymous blocks (again):

Bruce Leban bruce at leapyear.org
Mon May 13 21:10:14 CEST 2013


On Mon, May 13, 2013 at 11:33 AM, Juancarlo Añez <apalala at gmail.com> wrote:

> In Python, functions, methods, and classes are objects too, and their
> constructors are "class" and "def". But there's an asymmetry in the
> language in that those two constructors don't produce an assignable value.
>

Not all functions produce a useful value.

    [].append(1)
    [].sort()
    print(1)

Yes, these do return a value since functions always return a value, but
they don't return a useful value. Likewise, class and def have side effects
so if they were functions they would probably return None and you would
have the same issue that you couldn't usefully use them inside another
statement, just like this:

    x = print(y)

Def is not a constructor. It is an assignment statement.

    def f(x): return x+1
    f = lambda x: x+1

are equivalent. Python does not allow either one of these assignment
statements to be embedded in another statement. It does allow lambda
functions to be embedded in other statements. The issue here is essentially
that the def syntax allows more complex function syntax than lambda. And
the complaint is that that you have to declare a function "out of order"
and choose a name for it. This has the same problem:

    # can't do this
    case a.b[i]:
        when 0: pass
        when 1: pass
        when 2 ... 4: pass
        else: pass

    # can't do this either
    if (_value = a.b[i]) == 0: pass
    elif _value == 1: pass
    elif _value in 2 ... 4: pass
    else: pass

    # have to do this
    _value = a.b[i]
    if _value == 0: pass
    elif _value == 1: pass
    elif _value >= 2 and value <= 4: pass
    else: pass

This is a much more common scenario than wanting anonymous blocks. I'm not
proposing to change this. I'm just pointing out that if you're complaining
about not being able to assign a value inside a statement, there are more
common cases to look at.

--- Bruce
Latest blog post: Alice's Puzzle Page http://www.vroospeak.com
Learn how hackers think: http://j.mp/gruyere-security
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130513/20bac3fb/attachment.html>


More information about the Python-ideas mailing list