internal functions [Re: How do you feel ?]

Alex Martelli aleaxit at yahoo.com
Thu Aug 26 09:00:37 EDT 2004


Scott David Daniels <Scott.Daniels at Acm.Org> wrote:

> Howard Stearns wrote:
   ... 
> > Sorry. When I said "define a named function in a top-level assignment",
> > I didn't just mean using a reference to a previously defined function
> > (i.e., it's name), I meant actually defining the function in the 
> > assignment.

If you (Howard) mean horrors such as
    foo = lambda x: x + 23
the Pythonic way is
    def foo(x): return x + 23
with absolutely identical results.


> > In very complex cases, I lament the shear distance between the function
> > definition and the one place in the code where it is referenced. (Again,

What distance?  Put the def right before that 'one place in the code',
zero distance. 

> >>> assignments where I'd like create a function to use as the the value
> >>> being assigned. I don't know how to define a named function in a 

You sure do appear to ignore the equivalence between 'foo = lambda ...'
and def foo( ...'.  What do you think def _does_...?

> Maybe this is what you mean:
> 
> def dodef(val):
>      global globfunc
>      def globfunc(other):
>          return val, other
> 
> This works just fine.

It works, sort of, but each call to dodef steps right over the previous
value of global globfunc, and I think that may lead to nasty bugs.  I
much prefer the style:

def dodef(val):
    def anyfunc(other): return val, other
    return anyfunc

and if the caller wants to assign this function to name 'foofunc', it's
the caller's job to say

foofunc = dodef(23)


I think this is much more transparent and thus less error-prone.


Alex



More information about the Python-list mailing list