"def" vs "sub" (was RE: More random python observations from a perl programmer)

Michael Hudson mwh21 at cam.ac.uk
Fri Aug 20 14:27:37 CEST 1999


On 20 Aug 1999, Tom Christiansen wrote:
> In comp.lang.python, 
>     "Tim Peters" <tim_one at email.msn.com> writes:
> :In Python and in Perl (at least in the Perl I last tried that under) that
> :creates cyclic garbage:  makefac's lexicals have to contain a binding for
> :fac, and fac has to point back to makefac's lexicals in order to resolve
> :up-level references.  And that's (unrecoverable trash) the reason Python
> :doesn't have lexical closures today.  
> 
> That's quite right.  Doesn't python have some similar issue related
> to the use of bound methods?

Not in the simple case, no.

I take it you're thinking a bound method has a reference to the instance
which has a reference to the method? That's not the case, for, if you have
a class like this:

class Account:
    def __init__(self,amount):
        self.amount = amount
    def withdraw(self,amount):
        self.amount = self.amount - amount

then executing 

W=Account(50).withdraw

gets you a bound method which has a im_self member which refers to an
Account object which has a __class__ member which refers to the Account
class which has a __dict__ member which contains a function "withdraw" (as
in plain Python function).

(with apologies to the authors of sicp for using that example yet again,
and to all concerned for the length of that previous sentence).

>>> Account(50).withdraw.im_self.__class__.__dict__["withdraw"]
<function withdraw at 87cd30>

No cycles, see?

internally-y'rs
Michael





More information about the Python-list mailing list