Python 2.0

Michael Hudson mwh21 at cam.ac.uk
Wed Jun 9 12:57:44 CEST 1999


Jeremy Hylton <jeremy at cnri.reston.va.us> writes:

> >>>>> "DS" == Dan Schmidt <dfan at harmonixmusic.com> writes:
> 
>   DS> Hrvoje Niksic <hniksic at srce.hr> writes: | Kumar Balachandran
>   DS> <kumar*xspam*@*xspam*rtp.ericsson.se> writes: | | > What you
>   DS> said is quite wrong. Since Python provides closures, I can | >
>   DS> change my programming style to be completely different from the
>   DS> | > standard C or Fortran style and use a functional interface.
>   DS> | | Since when does Python provide closures?
> 
>   DS> The bytecodehacks module allows the creation of closures as I
>   DS> understand them.
> 
> Yes and no.  The bytecodehacks closures work right most of the time,
> but there some problems with them.  Hence, I would guess, the name
> "hacks."  

Quite. PLease note that the bytecodehacks resulted from me having an
idea that noone else seems to have had before and running away with it
as far as I could get it. The modules and functions that resulted from
this were really just illustrations of what the technique can do,
rather than solutions to any particular problem.

Having said that, if someone does find them useful, then that makes me
happy.

[explanantion of why "BCH closures" aren't quite like scheme closures]

> 
> def works():
>     sum = [0]
>     def add(x):
>         sum[0] = sum[0] + x
>     def sub(x):
>         sum[0] = sum[0] - x
>     cadd = closure.bind_locals(add)
>     csub = closure.bind_locals(sub)
>     cadd(2)
>     cadd(3)
>     csub(1)
>     return sum[0]

It probably wouldn't be all that hard to make bytecodehacks.closure
generate code like this automatically if it sees the substituted name
being mutated via STORE_FAST/STORE_GLOBAL.

Also note that the above code puts a mutable value into a code object,
something that isn't supposed to happen: (from the Language Reference)

| Unlike function objects, code objects are immutable and contain no
| references (directly or indirectly) to mutable objects.

Also Python expects to ba able to marshal code objects, so if you use
clsure.bind with an unmarshallable value there might be trouble.

Having said all that, it shouldn't cause any real problems (at least
not in 1.5.2).

Have a nice day!
Michael




More information about the Python-list mailing list