[Tutor] Adding dynamic methods (was RE: Function assignment)

Neil Schemenauer nas-pytut@python.ca
Fri Jun 13 13:47:45 2003


Zak Arntson wrote:
> How does this look to the Python interpreter? I mean, where is 'testA'
> stored?

This is pretty advanced stuff.  The short answer is that 'testA' is
stored in something called a closure.  A closure is basically a function
and it's lexical environment.

Poking around with dis might clear things up a little (maybe <wink>):

    >>> import dis
    >>> def msg(message):
    ...   def f():
    ...     return message
    ...   return f
    ... 
    >>> dis.dis(msg)
              0 SET_LINENO               1

              3 SET_LINENO               2
              6 LOAD_CLOSURE             0 (message)
              9 LOAD_CONST               1 (<code object f at 0x81682f8,
    file "<stdin>", line 2>)
             12 MAKE_CLOSURE             0
             15 STORE_FAST               1 (f)

             18 SET_LINENO               4
             21 LOAD_FAST                1 (f)
             24 RETURN_VALUE        
             25 LOAD_CONST               0 (None)
             28 RETURN_VALUE        
    >>> f = msg('testA')
    >>> f.func_closure
    (<cell at 0x8167b7c: str object at 0x8183b88>,)

In the above example, f is the closure.  The cell object refers to the
'testA' string.  The name func_closure is a bit confusing, IMO.  It does
not actually refer to the closure but instead refers to additional
information necessary to make the function into a closure.

> Are there any good references as to how this works?

The Python interpreter source code. :-)

  Neil