Functions as Objects, and persisting values

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Nov 5 21:20:08 CET 2007


Falcolas a écrit :
> Please help me understand the mechanics of the following behavior.
> 
> 
>>>>def d():
> 
> 	header = 'I am in front of '
> 	def e(something):
> 		print header + something
> 	return e
> 
> 
>>>>f = d()
>>>>f('this')
> 
> I am in front of this
> 
>>>>del(d)
>>>>f('this')
> 
> I am in front of this
> 
> The way I understand it, function d is an object,

Right.

> as is e. 

Right.

> However I
> don't quite grok the exact relationship between e and d.
 >
> Is e
> considered to be a subclass of 'd',

Nope.

> so that it has access to it's
> parent's __dict__ object, in order to access the value of 'header'? Or
> is this persistence managed in a different fashion?

As Diez said, it's called a lexical closure. A lexical closure is a 
function that captures and carries the lexical scope it was defined in 
with it - it 'closes over' it's environnement. Each time you call d, it 
returns a new function object (using the same code object) with a 
different environnement. You'll find this environement in f.func_closure.



More information about the Python-list mailing list