473,698 Members | 2,392 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6007
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_default s, _f2.func_closur e) 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
8481
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 problem. The program may crash unexpectedly while writing to the file. If so, my program should detect this during startup, and then (during startup) probably delete the data added to the file and redo the writing operation.
6
23599
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
3397
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 from the source. This data is written to file in a loop. My question. 1. Will it be useful to increase the file size initially then seek to 0 and start writing to file. whether there will be any performance improvements
5
45702
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 *air_address;
102
7069
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 of its documentation, it is a impeccability. it has or possesses properties of:
16
7180
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 unchanged). How can I do that in Python? Claudio Grondi
6
5267
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
2691
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, lsRecordType, lsXNbr, lsFiscYr, "Beg", CStr(H.BegBalAccDepn), CStr(H.BegBalCost), CStr(H.BegBalCostReval), CStr(H.BegBalDepCost), CStr(H.BegBalDepnReval)) The program is running from within a Virtual PC
89
3821
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 record inheritance (records do have operator overloading) The idea is to write a generic integer class with derived integer classess for 8 bit, 16 bit, 32 bit, 64 bit and 64 bit emulated.
0
8678
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9166
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9030
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8899
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4371
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.