Sunday, May 29, 2011

inner functions, how do they work?

When a higher order function returns a new function, a new context has been wrapped around the existing code object.  The code of that function is created once, at compile time.  There is absolutely no compiler involved at runtime, no new byte code is generated.

>>> def foo(n):
...    def bar():
...       print n
...    return bar
...
>>> a,b = foo(1), foo(2)
>>> a == b
False
>>> a()
1
>>> b()
2
>>> a.__code__ == b.__code__
True

2 comments:

  1. MAGICAL MIRACLES

    Also, perused this today:

    http://hg.python.org/cpython/file/default/Lib/fractions.py#l211

    It's neet.

    ReplyDelete
  2. Dear.I am very honored to introduce a external hard drive cnet products to you,it is very useful and free,and professional technical support.THANK YOU !

    ReplyDelete