nested functions

bruno at modulix onurb at xiludom.gro
Fri Apr 14 13:17:18 EDT 2006


Szabolcs Berecz wrote:
> On 14 Apr 2006 04:37:54 -0700, micklee74 at hotmail.com
> <micklee74 at hotmail.com> wrote:
> 
>>def a():
>>  def b():
>>    print "b"
>>  def c():
>>    print "c"
>>
>>how can i call c() ??
> 
> 
> Function c() is not meant to be called from outside function a().
> That's what a nested function is for: localizing it's usage and
> prevent cluttering the global namespace

There's actually more than this about Python's nested functions: they
can be returned from the outer function and then carry the environnement
in which they where created:

def trace(func):
    fname = func.__name__

    def traced(*args, **kw):
        print "calling func %s with *%s, **%s" % (fname, str(args), kw)
        try:
            result = func(*args, **kw)
        except Exception, e:
            print "%s raised %s" % (fname, e)
            raise
        else:
            print "%s returned %s" % (fname, str(result))
        return result

    return traced

def test(arg1, arg2='parrot'):
    print "in test, arg1 is %s" % arg1
    return arg2 * 3

test = trace(test)
test(42)


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list