473,545 Members | 2,776 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to wrap a class's methods?

I want to subclass an IMAP connection so that most of the
methods raise an exception if the returned status isn't 'OK'.
This works, but there's got to be a way to do it that doesn't
involve so much duplication:

class MyImap4_ssl(ima plib.IMAP4_SSL) :

def login(*args):
s,r = imaplib.IMAP4_S SL.login(*args)
if s!='OK':
raise NotOK((s,r))
return r

def list(*args):
s,r = imaplib.IMAP4_S SL.list(*args)
if s!='OK':
raise NotOK((s,r))
return r

def search(*args):
s,r = imaplib.IMAP4_S SL.search(*args )
if s!='OK':
raise NotOK((s,r))
return r

[and so on for another dozen methods]

--
Grant Edwards grante Yow! I OWN six pink
at HIPPOS!!
visi.com
Jul 18 '05 #1
14 1858
Grant Edwards wrote:
I want to subclass an IMAP connection so that most of the
methods raise an exception if the returned status isn't 'OK'.
This works, but there's got to be a way to do it that doesn't
involve so much duplication:

class MyImap4_ssl(ima plib.IMAP4_SSL) :

def login(*args):
s,r = imaplib.IMAP4_S SL.login(*args)
if s!='OK':
raise NotOK((s,r))
return r

def list(*args):
s,r = imaplib.IMAP4_S SL.list(*args)
if s!='OK':
raise NotOK((s,r))
return r

def search(*args):
s,r = imaplib.IMAP4_S SL.search(*args )
if s!='OK':
raise NotOK((s,r))
return r

[and so on for another dozen methods]


You could try something like (Untested!):

class Wrapper(object) :
def __init__(self, func):
self.func = func
def __call__(*args, **kwargs):
self, args = args[0], args[1:]
s, r = self.func(*args )
if s != 'OK':
raise NotOK((s, r))
return r

for func_name in ['login', 'list', 'search']:
func = Wrapper(getattr (imaplib.IMAP4_ SSL, func_name))
setattr(imaplib .IMAP4_SSL, func_name, func)

STeVe
Jul 18 '05 #2
Grant Edwards wrote:
I want to subclass an IMAP connection so that most of the
methods raise an exception if the returned status isn't 'OK'.
This works, but there's got to be a way to do it that doesn't
involve so much duplication:

class MyImap4_ssl(ima plib.IMAP4_SSL) :

def login(*args):
s,r = imaplib.IMAP4_S SL.login(*args)
if s!='OK':
raise NotOK((s,r))
return r

def list(*args):
s,r = imaplib.IMAP4_S SL.list(*args)
if s!='OK':
raise NotOK((s,r))
return r

def search(*args):
s,r = imaplib.IMAP4_S SL.search(*args )
if s!='OK':
raise NotOK((s,r))
return r

[and so on for another dozen methods]


A more tested version of my other email:

py> class C(object):
.... def f(self, *args):
.... print "f:", args
.... def g(self, *args):
.... print "g:", args
....
py> class D(C):
.... pass
....
py> class Wrapper(object) :
.... def __init__(self, func):
.... self.func = func
.... def __call__(self, *args):
.... print "wrapped"
.... return self.func(*args )
....
py> for name in ['f', 'g']:
.... wrapper = Wrapper(getattr (C, name))
.... setattr(D, name, new.instancemet hod(wrapper, None, D))
....
py> C().f()
f: ()
py> C().g(1)
g: (1,)
py> D().f()
wrapped
f: ()
py> D().g(1)
wrapped
g: (1,)
Jul 18 '05 #3
On 2005-02-17, Steven Bethard <st************ @gmail.com> wrote:
py> class C(object):
... def f(self, *args):
... print "f:", args
... def g(self, *args):
... print "g:", args
...
py> class D(C):
... pass
...
py> class Wrapper(object) :
... def __init__(self, func):
... self.func = func
... def __call__(self, *args):
... print "wrapped"
... return self.func(*args )
...
py> for name in ['f', 'g']:
... wrapper = Wrapper(getattr (C, name))
... setattr(D, name, new.instancemet hod(wrapper, None, D))


Thanks. The stuff provided by the "new" module is what I was
missing.

--
Grant Edwards grante Yow! Wait... is this a FUN
at THING or the END of LIFE in
visi.com Petticoat Junction??
Jul 18 '05 #4
Steven Bethard wrote:
Grant Edwards wrote:
I want to subclass an IMAP connection so that most of the
methods raise an exception if the returned status isn't 'OK'.
This works, but there's got to be a way to do it that doesn't
involve so much duplication:

class MyImap4_ssl(ima plib.IMAP4_SSL) :

def login(*args):
s,r = imaplib.IMAP4_S SL.login(*args)
if s!='OK':
raise NotOK((s,r))
return r
def list(*args):
s,r = imaplib.IMAP4_S SL.list(*args)
if s!='OK':
raise NotOK((s,r))
return r
def search(*args):
s,r = imaplib.IMAP4_S SL.search(*args )
if s!='OK':
raise NotOK((s,r))
return r
[and so on for another dozen methods]

You could try something like (Untested!):

class Wrapper(object) :
def __init__(self, func):
self.func = func
def __call__(*args, **kwargs):
self, args = args[0], args[1:]
s, r = self.func(*args )
if s != 'OK':
raise NotOK((s, r))
return r

for func_name in ['login', 'list', 'search']:
func = Wrapper(getattr (imaplib.IMAP4_ SSL, func_name))
setattr(imaplib .IMAP4_SSL, func_name, func)


You could probably also do this as a factory function, rather than as
a class (also untested!):

def Wrapper(func):
def wrapped(self, *args, **kwargs):
s, r = func(self, *args, **kwargs)
if s != 'OK':
raise NotOK((s,r))
return r
return wrapped

I believe that this will be semantically almost equivalent, but
conceptually slightly simpler.

Jeff Shannon
Jul 18 '05 #5
Grant Edwards wrote:
I want to subclass an IMAP connection so that most of the
methods raise an exception if the returned status isn't 'OK'.
This works, but there's got to be a way to do it that doesn't
involve so much duplication:

class MyImap4_ssl(ima plib.IMAP4_SSL) :

def login(*args):
s,r = imaplib.IMAP4_S SL.login(*args)
if s!='OK':
raise NotOK((s,r))
return r

def list(*args):
s,r = imaplib.IMAP4_S SL.list(*args)
if s!='OK':
raise NotOK((s,r))
return r

def search(*args):
s,r = imaplib.IMAP4_S SL.search(*args )
if s!='OK':
raise NotOK((s,r))
return r

[and so on for another dozen methods]


How about using a delegator:

class Wrapper:
funcs = ("login", "list", "search")
def __init__(self, classobj):
self.__wrapped = classobj()
def __getattr__(sel f, attr):
if attr in Wrapper.funcs:
def f(*args):
f1 = getattr(self.__ wrapped, attr)
s,r = f1(args)
if s != 'OK': raise NotOk((s,r))
return r
return f
# raise some exception here
imap = Wrapper(imaplib .IMAP4_SSL)

If you wrap all methods you can ignore the if-test. Instead of the
class object you can pass instances to the wrapper if you need
special arguments for initialization.

I don't like subclassing;)

Mathias

PS: note that we're wrapping the instance's methods, not the class's
methods!
Jul 18 '05 #6
On Thu, Feb 17, 2005 at 07:32:55PM +0000, Grant Edwards wrote:
I want to subclass an IMAP connection so that most of the
methods raise an exception if the returned status isn't 'OK'.
This works, but there's got to be a way to do it that doesn't
involve so much duplication:

class MyImap4_ssl(ima plib.IMAP4_SSL) :

def login(*args):
s,r = imaplib.IMAP4_S SL.login(*args)
if s!='OK':
raise NotOK((s,r))
return r

def list(*args):
s,r = imaplib.IMAP4_S SL.list(*args)
if s!='OK':
raise NotOK((s,r))
return r

def search(*args):
s,r = imaplib.IMAP4_S SL.search(*args )
if s!='OK':
raise NotOK((s,r))
return r

[and so on for another dozen methods]


something like this:

def NotOKVerified(o rig):
def f(*args):
s, r = orig(*args)
if s != 'OK':
raise NotOK((s,r))
return r
return f

class MyImap4_ssl(IMA P4_SSL):
pass

for method_name in ('login', 'list', 'search'):
setattr(MyImap4 _ssl, method_name, getattr(IMAP4_S SL, method_name))

?

I'd usually put big fat warnings around this code, and explain exaclty
why I need to do things this way...

--
John Lenton (jo**@grulic.or g.ar) -- Random fortune:
"To vacillate or not to vacillate, that is the question ... or is it?"

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.0 (GNU/Linux)

iD8DBQFCFPU3gPq u395ykGsRAmi/AJ9ETKZ6EZ5pgHf pibPOdPHbV24F0Q Cgltf4
kDEAtn7POsO/tXW0s2uuMZM=
=BjlO
-----END PGP SIGNATURE-----

Jul 18 '05 #7
Grant Edwards wrote:
On 2005-02-17, Steven Bethard <st************ @gmail.com> wrote:

py> class C(object):
... def f(self, *args):
... print "f:", args
... def g(self, *args):
... print "g:", args
...
py> class D(C):
... pass
...
py> class Wrapper(object) :
... def __init__(self, func):
... self.func = func
... def __call__(self, *args):
... print "wrapped"
... return self.func(*args )
...
py> for name in ['f', 'g']:
... wrapper = Wrapper(getattr (C, name))
... setattr(D, name, new.instancemet hod(wrapper, None, D))

Thanks. The stuff provided by the "new" module is what I was
missing.

No magic in the 'new' module - new.instancemet hod is just a synonym for the
method type:
import new, types
new.instancemet hod is types.MethodTyp e

True

Michael

Jul 18 '05 #8
On 2005-02-17, Mathias Waack <M.*****@gmx.de > wrote:
How about using a delegator:

class Wrapper:
funcs = ("login", "list", "search")
def __init__(self, classobj):
self.__wrapped = classobj()
def __getattr__(sel f, attr):
if attr in Wrapper.funcs:
def f(*args):
f1 = getattr(self.__ wrapped, attr)
s,r = f1(args)
if s != 'OK': raise NotOk((s,r))
return r
return f
# raise some exception here
imap = Wrapper(imaplib .IMAP4_SSL)

If you wrap all methods you can ignore the if-test.
I'm not, and the other methods should behave "normally":

class Wrapper:
funcs = ("login", "list", "search")
def __init__(self, classobj):
self.__wrapped = classobj()
def __getattr__(sel f, attr):
if attr in Wrapper.funcs:
def f(*args):
f1 = getattr(self.__ wrapped, attr)
s,r = f1(args)
if s != 'OK': raise NotOk((s,r))
return r
else:
f = getattr(self.__ wrapped, attr)
return f
PS: note that we're wrapping the instance's methods, not the class's
methods!


You're right.

--
Grant Edwards grante Yow! "THE LITTLE PINK
at FLESH SISTERS," I saw them
visi.com at th' FLUROESCENT BULB
MAKERS CONVENTION...
Jul 18 '05 #9
On 2005-02-17, Michael Spencer <ma**@telcopart ners.com> wrote:
Thanks. The stuff provided by the "new" module is what I was
missing.


No magic in the 'new' module - new.instancemet hod is just a synonym for the
method type:
>>> import new, types
>>> new.instancemet hod is types.MethodTyp e

True


Thanks -- I didn't know that either.

--
Grant Edwards grante Yow! I joined scientology
at at a garage sale!!
visi.com
Jul 18 '05 #10

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

Similar topics

3
10754
by: JHR | last post by:
Hey all, I'm trying to make a sidebar box float to the right of various items, and for those items to wrap if a user shrinks his browser window. Instead, in every browser I've tried except for Internet Explorer (in Safari, Firefox, and other Mozilla-types), the box ends up overlapping with the second and third rows of the text (which are in...
11
1497
by: John Salerno | last post by:
My general problem with events seems to be that there are so many parts to them, and I'm not sure where they all go or when you use which parts. For example, there's the delegate, the event name, the event handler, then the coding that wires it together. For the most part, I do understand these things, but I get confused when it comes to...
3
1989
by: _BNC | last post by:
I have an old C DLL that I want to access via C#. I'm doing this via an outer DLL that wraps the old C DLL in an unmanaged C++ class, which is in turn wrapped in a Managed C++ class. Both these unmanaged C++ and managed C++ classes are compiled into a single assembly (DLL) that is accessed by C#. <--> <--> old dll new...
1
1704
by: kathy | last post by:
I have posted my problem before and still not feel confused. Anyone know what is the problem? In my Win32 dll, I defined: #ifdef DllExport #define UNMANAGED_API __declspec(dllexport) #else #define UNMANAGED_API __declspec(dllimport) #endif
2
4143
by: YeJianWei | last post by:
I need to wrap a MFC extension Dll with export class(let's suppose it's named CA) so we could use it in C#. The dll is provided by third party vendor which means I couldn't modify it. A managed c++ library project was created to wrap this dll with a __gc class(let's suppose it's named CGA). class CGA contain an instance of class CA and...
6
3454
by: 314ccc | last post by:
I have some old code that uses very large c style arrays extensively. I am to the point where I need to write some new methods that access this data. Instead of passing this data as a pointer and a count, I'd like to pass it as a const collection reference. The problem is that I can't seem to figure out how to intiialize any of the STL...
5
4663
by: pamela fluente | last post by:
I have been posting this question with no success. I do not know if I am not being clear of the question is too difficult :-)) or unclear. It seems to me that the need to wrap a collection is quite common in real world programs. I am having problem to understand how I can wrap collections in System.Collections.Generic. For example I want...
2
2547
by: =?Utf-8?B?Y2hyaXNiZW4=?= | last post by:
Hi, I have some C++ static library which I would like to wrap and use in C# applications. It appears that I have two options. 1. Wrap the static library as dynamic library (dll), use unmanaged C++. Then invoke the method in C# by DllImport. 2. Wrap the static lib using managed C++, which will create a dll as .NET assembly, so C#...
4
2197
by: Greg Ewing | last post by:
I'm creating a COM server in Python that will have one main class, with methods that create and return instances of other classes. I've found that I need to use win32com.server.util.wrap and unwrap on these objects when they pass over a COM connection. This doesn't seem very convenient, especially for methods that can be called either via...
0
7499
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...
0
7432
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...
0
7943
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...
1
7456
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...
0
7786
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...
0
6022
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...
0
5076
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...
0
3490
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...
1
1919
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.