473,326 Members | 2,813 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Writing func_closure?

Hi all,

by reading through the docs, the func_closure attribute of function objects is
listed as writable. Yet, nowhere does it say _how_ to write to it. I am
trying to do a run-time modification of a function's closure, where I want to
modify the value of one of the variables in the closure. But the closure
appears as a tuple of 'cell' objects:

In [21]: def wrap(x):
....: def f(y):
....: return x+y
....: return f
....:

In [22]: f1=wrap('hello')

In [23]: f1.func_closure
Out[23]: (<cell at 0x4168bcd4: str object at 0x41bc0080>,)

My question is, how can I create one of these cell objects to stuff into the
closure (I want to do this from pure Python, not C extensions).

The docs mention this as 'possible', but don't provide a single example (though
they don't really specify if it can be done in python or only in C). The 'new'
module is equally useless, since new.function() comes without any examples:

In [25]: new.function?
Type: type
Base Class: <type 'type'>
String Form: <type 'function'>
Namespace: Interactive
Docstring:
function(code, globals[, name[, argdefs[, closure]]])

Create a function object from a code object and a dictionary.
The optional name string overrides the name from the code object.
The optional argdefs tuple specifies the default argument values.
The optional closure tuple supplies the bindings for free variables.

See that last line? Nowhere does it say what how the closure tuple is supposed
to be constructed. I tried a bunch of things, and none of my shot-in-the-dark
attempts got me anywhere.

Any help on this would be much appreciated.

Best,

f

Jul 19 '05 #1
5 5990
Fernando Perez wrote:
I am trying to do a run-time modification of a function's closure,
where I want to modify the value of one of the variables in the closure.
Out of curiosity, why?
In [21]: def wrap(x):
....: def f(y):
....: return x+y
....: return f
....:

In [22]: f1=wrap('hello')

In [23]: f1.func_closure
Out[23]: (<cell at 0x4168bcd4: str object at 0x41bc0080>,)

My question is, how can I create one of these cell objects to stuff into the
closure (I want to do this from pure Python, not C extensions).

f1.func_closure[0].__class__() Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot create 'cell' instances

Hmmm, that didn't work so well.
f1.func_closure = f1.func_closure Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: readonly attribute

Closer inspection of the docs <http://docs.python.org/ref/types.html>
reveals that it is not writable after all. Therefore the only way I can
see to do it without writing an extension is to generate some dummy
function and copy the func_closure attribute from it. Luckily, you have
already produced a factory for such a function:
f1(" there")\ 'hello there' _f2 = wrap("howdy")
f1 = new.function(f1.func_code, f1.func_globals, f1.func_name, f1.func_defaults, _f2.func_closure) f1(" there")

'howdy there'

Mix-and-match functions! What will they think of next?
--
Michael Hoffman
Jul 19 '05 #2
Michael Hoffman wrote:
Fernando Perez wrote:
> I am trying to do a run-time modification of a function's closure,
> where I want to modify the value of one of the variables in the closure.
Out of curiosity, why?


Oh, I was just trying to play a little trick inside a tight loop where I would
modify on the fly the function's closure to change a parameter. I can do it in
a million ways, but at creation time, the closure approach provides the
cleanest syntax. But at runtime, I have an algorithm that needs to modify
certain parameters many times, and the least-expensive way would be to be able
to write directly into the closure.
Closer inspection of the docs <http://docs.python.org/ref/types.html>
reveals that it is not writable after all. Therefore the only way I can
Ah, the docs have improved. I'm using 2.3.4, and the same page:

http://www.python.org/doc/2.3.4/ref/types.html

only says:

Of these, func_code, func_defaults, func_doc/__doc__, and func_dict/__dict__ may
be writable; the others can never be changed.

That's what led me to believe it could be done. Thanks for pointing me to the
2.4 docs, which are much less ambiguous.

see to do it without writing an extension is to generate some dummy
function and copy the func_closure attribute from it. Luckily, you have
already produced a factory for such a function:


Yes, I knew of the new.function() approach, but the problem is that I don't know
how to make a fresh closure for it. I can reuse the closure from a different
function, but the docs don't say how to make a valid closure tuple. This is
the typical problem of the stdlib docs, which under-specify what is supposed to
go into a call and don't give at least a specific example.

Many thanks though, I'll probably end up using a less dirty hack :)

Cheers,

f

Jul 19 '05 #3
Fernando Perez wrote:
I can reuse the closure from a different
function, but the docs don't say how to make a valid closure tuple. This is
the typical problem of the stdlib docs, which under-specify what is supposed to
go into a call and don't give at least a specific example.


As far as I know, there is currently no supported way
of directly creating or modifying cell objects from Python;
it can only be done by some obscure trickery. So the docs
are telling the truth here, in a way. :-)

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
Jul 19 '05 #4
Greg Ewing wrote:
As far as I know, there is currently no supported way
of directly creating or modifying cell objects from Python;
it can only be done by some obscure trickery. So the docs
are telling the truth here, in a way. :-)


In a twisted, convoluted way :)

But thanks for the clarification (which IMHO belongs in the docs). Oh well, it
was a dirty hack anyways, so it's probably best not done.

Cheers,

f

Jul 19 '05 #5
Fernando Perez wrote:
Yes, I knew of the new.function() approach, but the problem is that I don't know
how to make a fresh closure for it. I can reuse the closure from a different
function, but the docs don't say how to make a valid closure tuple.
def makeclosure(x): .... def _f():
.... x
.... return _f.func_closure
.... makeclosure(42)

(<cell at 0x4613bc: int object at 0x4a3e4c>,)

OK, that's kind of limited. God only knows what happens when there is
more than one variable, although you could add extra levels of hackery
to do with that.
Many thanks though, I'll probably end up using a less dirty hack :)


*Excellent* idea.
--
Michael Hoffman
Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

48
by: Joseph | last post by:
Hi I'm writing a commercial program which must be reliable. It has to do some basic reading and writing to and from files on the hard disk, and also to a floppy. I have foreseen a potential...
6
by: Sebastian Kemi | last post by:
How should a write a class to a file? Would this example work: object *myobject = 0; tfile.write(reinterpret_cast<char *>(myobject), sizeof(*object)); / sebek
3
by: ishekar | last post by:
Hi, I have an application where i want to write data to a file, the data is being sent from an external source. I know the total size of the data and then i retrieve the data in small segments...
5
by: Jeong-Gun Lee | last post by:
I'm writing a code of writing a value to a specific memory address. ================================================================= #include <stdio.h> int main() { long air; long...
102
by: Xah Lee | last post by:
i had the pleasure to read the PHP's manual today. http://www.php.net/manual/en/ although Pretty Home Page is another criminal hack of the unix lineage, but if we are here to judge the quality...
16
by: Claudio Grondi | last post by:
I have a 250 Gbyte file (occupies the whole hard drive space) and want to change only eight bytes in this file at a given offset of appr. 200 Gbyte (all other data in that file should remain...
6
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
3
by: Barry Flynn | last post by:
Hi I am working with a VB 2005 program which has been converted from VB6. It writes data out to a flat file, with code like the following line WriteLine(riFileNo, "Hist", lsAssetID,...
89
by: Skybuck Flying | last post by:
Hello, This morning I had an idea how to write Scalable Software in general. Unfortunately with Delphi 2007 it can't be done because it does not support operating overloading for classes, or...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.