syntax for code blocks

Chris Angelico rosuav at gmail.com
Tue May 1 11:28:51 EDT 2012


On Wed, May 2, 2012 at 1:11 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> So in this case, even though Python is slightly more verbose, and forces
> you to have the discipline of writing named functions ahead of time, this
> is actually a *good* thing because it encourages you to test them.
>
> If the callbacks are trivial functions, the Pythonic way is to use
> lambdas:
>
> func(some_args, {'when_odd': lambda n: n-1,
>                 'when_prime': lambda n: n**2 - 1,
>                 ...})
>
> although I would discourage that unless they are *really* trivial. But
> for callbacks of any complexity, they will need to be tested, otherwise
> how do you know they do what you want them to do?

Agreed. At work, I'm currently shoveling through a pile of Javascript
code (about 500KB of it, one file) that largely looks like this:

FOO={}
FOO.bar={
    init:function() {
        // ... initialization code
    },
    quux:function(a,b) {
        //code for this function
    },
    ajaxrequest:function() {
        var blah,blah;
        blah;
        return {
            foo:function() {
                blah;
            }
        };
    }(),
    bleh:blah
}

It's all anonymous functions assigned to member variables. It's not
easy to debug, and refactoring the code into something simpler is a
weeks-long job. I know it is because I've already spent two on it. Oh,
and notice how ajaxrequest isn't actually declaring a function at all,
it's calling a function and using its return value? Important
information like that is buried away instead of being in the function
signature. Plus, to make matters worse, many of the function and
object names are reused, so FOO.bar.ajaxrequest.foo() is completely
different from FOO.something.else.foo() and both have just
"foo:function()" as their signature.

Write your code out of line unless it REALLY wants to be inline. Name
the functions unless they're trivial.

And yes, I did say that I would do them as in-line lambdas. I don't
really see much value in the callback system you have here unless
either they ARE that trivial, or it's patently obvious that they need
to be functions, so I still stand by what I said.

ChrisA



More information about the Python-list mailing list