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

Home Posts Topics Members FAQ

Help in using introspection to simplify repetitive code

Hello.
I'm writing a proxy class, i.e: a class whose methods mostly delegate
their functionality to other class object. Most of the methods (which
are quite a lot) defined in the class would end up being:

def thisIsTheMethod Name(self):
self._handlerCl ass.thisIsTheMe thodName()

The handler object is the same in all methods.

I was wondering if there is a way to simplify this proxy class, maybe
using some pythonic technique like metaclasses, introspection.. . any
suggestion is appreciated.

Thanks,

Javier Sanz

Aug 20 '06 #1
6 1665

js********@gmai l.com wrote:
Hello.
I'm writing a proxy class, i.e: a class whose methods mostly delegate
their functionality to other class object. Most of the methods (which
are quite a lot) defined in the class would end up being:

def thisIsTheMethod Name(self):
self._handlerCl ass.thisIsTheMe thodName()

The handler object is the same in all methods.

I was wondering if there is a way to simplify this proxy class, maybe
using some pythonic technique like metaclasses, introspection.. . any
suggestion is appreciated.

Thanks,

Javier Sanz
http://docs.python.org/ref/attribute...s.html#l2h-206

Aug 20 '06 #2

<js********@gma il.comwrote in message
news:11******** *************@7 5g2000cwc.googl egroups.com...
Hello.
I'm writing a proxy class, i.e: a class whose methods mostly delegate
their functionality to other class object. Most of the methods (which
are quite a lot) defined in the class would end up being:

def thisIsTheMethod Name(self):
self._handlerCl ass.thisIsTheMe thodName()
Are these parameterless static methods
or should this be self._handlerCl ass.thisIsTheMe thodName(self)
or does self get auto-bound even though not a _handlerClass instance?
(I have never needed or done such delegation.)
The handler object is the same in all methods.

I was wondering if there is a way to simplify this proxy class, maybe
using some pythonic technique like metaclasses, introspection.. . any
suggestion is appreciated.
My immediate thought would be to start with

_forwarded = set(......) # of forwarded method names
def __getattr__(sel f, name):
if name in _forwarded: return getattr(self._h andlerClass, name)

but I am not sure if this gives the right wrapping and binding.

Terry Jan Reedy

Aug 20 '06 #3
As you mention, wether the methods take arguments or not is something
to have into account.
And they do take arguments, and a variable number of them, so AFAIK
hooking with __getattr__ or __getattribute_ _ will not work, as you can
only get the method name with that. I was thinking of some __call__
overriding, but I've never done it before and I don't know if this
could be the way to go.
--
Un saludo,

Javier

Aug 21 '06 #4
js********@gmai l.com wrote:
And they do take arguments, and a variable number of them, so AFAIK
hooking with __getattr__ or __getattribute_ _ will not work, as you can
only get the method name with that.
why not just return the bound method *object* (a callable), and let the
caller call that as usual (see Terry's last example).

(hint: x.foo() can be written f=getattr(x,"fo o"); f())
</F>

Aug 21 '06 #5

Fredrik Lundh wrote:
js********@gmai l.com wrote:
And they do take arguments, and a variable number of them, so AFAIK
hooking with __getattr__ or __getattribute_ _ will not work, as you can
only get the method name with that.

why not just return the bound method *object* (a callable), and let the
caller call that as usual (see Terry's last example).

(hint: x.foo() can be written f=getattr(x,"fo o"); f())
</F>
I can tell you from my experience that this works; I've used this
before to make something very much like this proxy-class:

class RequestCalculat ions(object):
def __init__(self, request):
self.serviceTyp e, self.facade =
makeMessageFaca deInstance(requ est)
return

def __getattr__(sel f, name):
return getattr(self.fa cade, name)

(rest of the code omitted)

Cheers,

--Tim

Aug 21 '06 #6
js********@gmai l.com a écrit :
As you mention, wether the methods take arguments or not is something
to have into account.
And they do take arguments, and a variable number of them, so AFAIK
hooking with __getattr__ or __getattribute_ _ will not work, as you can
only get the method name with that.
Nope. Defining __getattr__ is the canonical pythonic way to do
delegation. Remember that in Python, functions and methods are objects
too and can be passed around/returned etc just like any other object.

Aug 27 '06 #7

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

Similar topics

0
1371
by: Carlos Ribeiro | last post by:
Hello all, While studying some of the templating systems available for Python, I've come up with an idea to implement templates using decorators. The following code snippet runs in Python 2.3; a few 2.4 only extensions are shown as comments. Please note that I have shamelessly copied the trim function from PEP 257, because it's needed to have the strings properly formatted. ============================
13
2092
by: Steven Scaife | last post by:
I have decided to re-write the intranet site i created over a year ago. The coding is pretty awful and hard to read cos I made the mistake of not putting comments in or putting crappy comments in with the code. So I have decided to try and make things neater by grouping it into subs. So i have a sub to create the variables, a sub for the connection etc. Only problem is when i call my subs, it says that the variable is undefined. If i...
4
2651
by: Benjamin Rutt | last post by:
I'm trying to learn about introspection in Python. my ultimate goal is to be able to build a module "text database" of all modules that are in the sys.path, by discovering all candidate modules (I've already done that), importing all of them, and then introspecting on each module to discover its functions, globals and classes. But for now I am having a problem with the latter. I would like to import a module and figure out the names of...
4
1830
by: Steven T. Hatton | last post by:
Has there been any substantial progress toward supporting introspection/reflection in C++? I don't intend to mean it should be part of the Standard. It would, nonetheless, be nice to have a generally accepted means of providing introspection. My inclination is to have two general categories of introspection: dynamic introspection, and static intospection. In situations where it makes sense to use virtual functions and their...
98
4577
by: tjb | last post by:
I often see code like this: /// <summary> /// Removes a node. /// </summary> /// <param name="node">The node to remove.</param> public void RemoveNode(Node node) { <...> }
4
1769
by: MC felon | last post by:
hello. i tried this for a simple push_back action..... it says "ostream - no such file or directory" #include <iostream> #include <conio2.h> #include <string> #include <ostream> int main() {
3
1346
by: James Stroud | last post by:
Hello, I wanted to automagically generate an instance of a class from a dictionary--which might be generated from yaml or json. I came up with this: # automagical constructor def construct(cls, adict): dflts = cls.__init__.im_func.func_defaults vnames = cls.__init__.im_func.func_code.co_varnames
14
4201
by: Dave Rahardja | last post by:
Is there a way to generate a series of statements based on the data members of a structure at compile time? I have a function that reverses the endianness of any data structure: /// Reverse the endianness of a data structure "in place". template <typename T> void reverseEndian(T&); Using boost, it is possible to provide the default implementation for all POD
4
3406
by: mirandacascade | last post by:
Not sure if 'introspection' is the correct term, so apologies if subject line is off-base. 1) Is there any functionality that answers the question: what module am I in? 2) Is there any functionality that answers the question: what function/ subroutine am I in? Suppose, for example, I wanted to write information to a log...each entry in the log is along the lines of:
0
8672
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
9021
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
8892
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
8860
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...
0
7712
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
6518
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
5860
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
4614
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3038
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.