[Python-ideas] Proposal for function expressions

Chris Perkins chrisperkins99 at gmail.com
Mon Jul 13 12:51:27 CEST 2009


On Sun, Jul 12, 2009 at 8:31 PM, Jim Jewett<jimjjewett at gmail.com> wrote:
> So the named and anoymous functions don't share scope in any way?
>
> Then what is the advantage?  Is putting the call ahead of the def that
> valuable for making the code clear?

Yes, exactly - or at least, I think it is. I have found that putting
the call before the def adds a surprising amount readability. I came
to this conclusion from doing primarily JavaScript for the last couple
of years - there, you have a choice of whether to predefine a local
function, or to put one inline. eg:

  var callback = function(result) {
    // 10 lines of code...
  };
  make_ajax_call(url, callback);

vs.

  make_ajax_call(url, function(){
    // 10 lines of code...
  });

I have come to hate the former style, and find myself frequently
refactoring it into the latter, because the main thrust of what this
code does is summed up by "make_ajax_call(url, ..)", so that is what I
want to see first - not way down at the end, like an afterthought.

In other words, I think code that puts things in the opposite order
from the way you think of them is harder to read.

Another example: if I'm thinking that what I want to do is "substitute
some stuff in a string", then I want to start by typing/reading
"re.sub(...)", and not "def some_made_up_name(...):"

re.sub(pat, &, s) do(m):
    # several lines of code

vs.

def temp(m):
    # several lines of code
re.sub(pat, temp, s)

The latter relegates the key line of code to the very last line,
making it harder to see at a glance what it does.

So yes, the point of this really is just to allow you to write code
"in the right order".

I guess I should have made all this clearer in my original email :)


Chris Perkins



More information about the Python-ideas mailing list