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

Steven D'Aprano steve at pearwood.info
Sat Jul 18 18:36:45 CEST 2009


On Sat, 18 Jul 2009 10:45:44 pm Daniel Stutzbach wrote:
> On Fri, Jul 17, 2009 at 7:39 PM, Steven D'Aprano 
<steve at pearwood.info>wrote:
> > In a real sense, the proposed 'where' block breaks the flow of
> > reading code. Normally, reading a function proceeds in an orderly
> > fashion from the start of the function to the end in (mostly)
> > sequential order, a bottom-up process:
>
> Normally, that's true, but that's not true when defining a
> sub-function. Consider the following:
>
> def foo(items):
>     def compute_sort_value(item):
>         # compute value based on item's properties
>         return value
>    # a bunch of other code is here
>     items.sort(compute_sort_value)
>
> Above, the body of compute_sort_value appears long before it is
> executed. 

Right. That's no different from this case:


def bar(items):
    c_s_v = list(
        # comment goes here
        'csv')
    # a bunch of other code is here
    items.extend(c_s_v)


def is an executable statement which creates a function; list() is an 
executable function (technically a type) which creates an list.

In your example, the inner function compute_sort_value is created when 
foo is executed. Python functions are first class objects, and so you 
can create functions and pass them to functions without necessarily 
calling the __call__ method.

In my example, the inner list c_s_v is created when bar is executed. 
Lists are first class objects, and so you can create lists and pass 
them to functions without necessarily calling the __getitem__ method.

In both functions, the objects compute_sort_value and c_s_v are created 
before they are used.


> Now consider: 
>
> def foo(items):
>     # a bunch of other code is here
>     items.sort(key=mean) where:
>         def compute_sort_value(item):
>             return value

Presumably you meant to write:

    items.sort(key=compute_sort_value) where:


> Now, the body of compute_sort_value appears exactly where it is
> executed: within the call to items.sort().

No it doesn't. The function definition appears outside the call to 
sort(). For the function definition to appear inside the call to sort, 
you'd need to write something like:

    items.sort(key=lambda item: value)

In this case, the lambda only occurs inside the call to sort() -- it's 
inaccessible to anything else (excluding trickery inside of sort() 
itself). By comparison, the compute_sort_value() function exists inside 
the where-block, and therefore is accessible to everything else inside 
that block:

    items.sort(key=compute_sort_value) where:
        def compute_sort_value(item):
            return value
        print compute_sort_value('testing testing 1 2 3')





-- 
Steven D'Aprano



More information about the Python-ideas mailing list