473,668 Members | 2,446 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Curried class methods?

I'm trying to dynamically generate class methods which have access to
some state passed in at creation time. (Basically as a workaround to
twisted's trial not having a way to dynamically add stuff. Plain
unittest seems to have TestSuite, but the trial runner doesn't know
about it.)

My first attempt might better illustrate this -

class Foo:
def generalized(sel f, ctx):
print 'my ctx is %r' % ctx

for i in ['a','b','c']:
setattr(Foo, i, lambda self: self.generalize d(i))

foo = Foo()
foo.a()
foo.b()
foo.c()

but this prints "my ctx is c" three times; I'd hoped for a, b, c, of
course. After reading
<http://mail.python.org/pipermail/python-list/2004-July/229478.html>, I
think I understand why this is - "i" doesn't actually get added to each
new function's context; they just reference the global one. Even if I
do this:

def builder():
for i in ['a','b','c']:
setattr(Foo, i, lambda self: self.generalize d(i))
builder()

they'll just keep a reference to the context that was made on entry to
builder() and share it, so the modifications builder() makes to i are
reflected in all three functions.

Okay, take two. I tried this:

try:
from functional import partial
except ImportError:
...partial pasted from PEP 309...

for i in ['a','b','c']:
setattr(Foo, i, partial(Foo.gen eralized, ctx=i))

but when I try to call foo.a(), I get this error:

Traceback (most recent call last):
File "./foo.py", line 35, in ?
foo.a()
File "./foo.py", line 25, in __call__
return self.fn(*(self. args + args), **d)
TypeError: unbound method generalized() must be called with Foo
instance as first argument (got nothing instead)

If I add a debug print to partial.__call_ _,

print 'partial.__call __(args=%r, kw=%r, self.kw=%r)' \
% (args, kw, self.kw)

I see:

partial.__call_ _(args=(), kw={}, self.kw={'ctx': 'a'})

I'd first expected foo.a() to be equivalent to Foo.a(self), but instead
it's like Foo.a(). There must be magic that does the equivalent of

class Foo:
def __init__(self):
a = partial(a, self)

for real Python functions and not for my partial object.

With this __init__ magic, I guess I have something that works. I have
to apply the partial twice, though - if I do everything in the
__init__, my new functions won't exist by the time trial's
introspection kicks in, so they'll never get called. My ugly hack has
gotten even uglier.

Does anyone know of a better way to do this?

Thanks,
Scott

Aug 17 '06 #1
3 1488
On 2006-08-17, Scott Lamb <sr****@gmail.c omwrote:
I'm trying to dynamically generate class methods which have access to
some state passed in at creation time. (Basically as a workaround to
twisted's trial not having a way to dynamically add stuff. Plain
unittest seems to have TestSuite, but the trial runner doesn't know
about it.)

My first attempt might better illustrate this -

class Foo:
def generalized(sel f, ctx):
print 'my ctx is %r' % ctx

for i in ['a','b','c']:
setattr(Foo, i, lambda self: self.generalize d(i))

foo = Foo()
foo.a()
foo.b()
foo.c()

but this prints "my ctx is c" three times; I'd hoped for a, b, c, of
course. After reading
<http://mail.python.org/pipermail/python-list/2004-July/229478.html>, I
think I understand why this is - "i" doesn't actually get added to each
new function's context; they just reference the global one. Even if I
do this:
Try this instead as the for loop

for i in ['a','b','c']:
setattr(Foo, i, lambda self, a=i: self.generalize d(a))

--
Antoon Pardon
Aug 17 '06 #2
Scott Lamb wrote:
I'm trying to dynamically generate class methods which have access to
some state passed in at creation time. (Basically as a workaround to
twisted's trial not having a way to dynamically add stuff. Plain
unittest seems to have TestSuite, but the trial runner doesn't know
about it.)

My first attempt might better illustrate this -

class Foo:
def generalized(sel f, ctx):
print 'my ctx is %r' % ctx

for i in ['a','b','c']:
setattr(Foo, i, lambda self: self.generalize d(i))

foo = Foo()
foo.a()
foo.b()
foo.c()

but this prints "my ctx is c" three times; I'd hoped for a, b, c, of
course.
def build(j):
setattr(Foo, j, lambda self: self.generalize d(j))
for i in ["a","b","c"]:
build(i)

Each call of the the build function creates its own cell "j" that the
lambda references.
Carl Banks

Aug 17 '06 #3
Thanks, Antoon and Carl. Just tried your solutions - both work and are
much cleaner than mine.

Aug 17 '06 #4

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

Similar topics

0
1041
by: Holger Türk | last post by:
Hello, a common pattern to write curried functions (i.e. without the need for a special partial application syntax, like in PEP 309) is like in this example: def functionLock (lk): def transform (fn): def lockedApply (*argl, **argd): lk.acquire ()
4
8014
by: Neil Zanella | last post by:
Hello, I would like to know whether it is possible to define static class methods and data members in Python (similar to the way it can be done in C++ or Java). These do not seem to be mentioned in "Learning Python" by Mark Lutz and David Ascher. It seems like they are a relatively new feature... It seems to me that any truly OO programming language should support these so I'm sure that Python is no exception, but how can these be...
18
6945
by: John M. Gabriele | last post by:
I've done some C++ and Java in the past, and have recently learned a fair amount of Python. One thing I still really don't get though is the difference between class methods and instance methods. I guess I'll try to narrow it down to a few specific questions, but any further input offered on the subject is greatly appreciated: 1. Are all of my class's methods supposed to take 'self' as their first arg? 2. Am I then supposed to call...
6
2496
by: svend | last post by:
Hey there, I was thinking about some curried functions in JavaScript, and I made this: <script> function add(a, b, c) { if (arguments.length == 1) { return function (d,e) {return a + d + e} }
7
2106
by: WXS | last post by:
Vote for this idea if you like it here: http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=5fee280d-085e-4fe2-af35-254fbbe96ee9 ----------------------------------------------------------------------------- This is a consortium of ideas from another thread on topic ----------------------------------------------------------------------------- One of the big issues of organizing items within a class, is there are many...
0
2822
by: emin.shopper | last post by:
I had a need recently to check if my subclasses properly implemented the desired interface and wished that I could use something like an abstract base class in python. After reading up on metaclass magic, I wrote the following module. It is mainly useful as a light weight tool to help programmers catch mistakes at definition time (e.g., forgetting to implement a method required by the given interface). This is handy when unit tests or...
9
5840
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context, culture, InValue);
61
2949
by: Sanders Kaufman | last post by:
I'm wondering if I'm doing this right, as far as using another class object as a PHP class property. class my_baseclass { var $Database; var $ErrorMessage; var $TableName; var $RecordSet; function my_baseclass(){ $this->TableName = "";
2
1777
by: fgh.vbn.rty | last post by:
Hi, I'm not sure if i'm asking the question correctly but anyway here it is. Say I have 3 classes - class A, class B, class R. 1) A and B are the building blocks and R is like a repository that stores objects of A and B. 2) A is at the lowest level and should "know about" only other As. B should know only about As and other Bs.
0
8459
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
8889
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
8790
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...
0
8652
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6206
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
5677
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4202
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...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2782
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.