473,781 Members | 2,718 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python interceptor package

Hi group

I'm looking for a Python interceptor package, which will allow me to
intercept the invocation of any function or method call.

For those familiar with CORBA interceptors, this should be roughly
analogous (though simpler as we don't have a client and server side)
but should work for any native Python invocation.

A trivial but practical use of such interceptors could be to log such
invocations (also see the 'Interceptor pattern' from POSA2 by Douglas
Schmidt, et. al.)

In particular
- It should be possible to intercept
- Method calls (instance, class and static methods), either for
a specific instance or for all instances of a class (possibly
distinguishing between inherited and new or overridden methods)
- Function calls
- Calls to other callables
- It should not require any modification to existing modules
in a system
- It should be possible to install and remove such interceptors
at run-time (deriving a class and overriding a method is not
an option).
- It should be possible to install multiple interceptors (serving
different purposes) for any function/method

Has any work been done in this direction?

Thanks
Fritz
Jul 18 '05 #1
4 3666
Fritz Bosch wrote:
Hi group

I'm looking for a Python interceptor package, which will allow me to
intercept the invocation of any function or method call.

For those familiar with CORBA interceptors, this should be roughly
analogous (though simpler as we don't have a client and server side)
but should work for any native Python invocation.

A trivial but practical use of such interceptors could be to log such
invocations (also see the 'Interceptor pattern' from POSA2 by Douglas
Schmidt, et. al.)

In particular
- It should be possible to intercept
- Method calls (instance, class and static methods), either for
a specific instance or for all instances of a class (possibly
distinguishing between inherited and new or overridden methods)
- Function calls
- Calls to other callables
- It should not require any modification to existing modules
in a system
- It should be possible to install and remove such interceptors
at run-time (deriving a class and overriding a method is not
an option).
- It should be possible to install multiple interceptors (serving
different purposes) for any function/method

Has any work been done in this direction? You seem to look for:
import sys
sys.settrace(.. .)
(Python interpreter hook), it should do the job.

Ciao,
Dominic

Thanks
Fritz

Jul 18 '05 #2
Dominic <no****@nospam. no> wrote in message news:<ca******* ***@news.uni-kl.de>..
....
sys.settrace(.. .)
(Python interpreter hook), it should do the job.

....

What I'm looking for is an Interceptor class whose
constructor would interpose its (callable) instance
between a caller and a specified function or method,
and whose 'destroy' method would remove the interposition.

One would typically subclass the Interceptor class to
achieve the required interceptor behaviour.

sys.settrace looks like a possible starting point to create
such a package, allthough it is somewhat indiscriminate for my
purposes (I want to be selective about what I intercept).
Of course the selection can occur inside the trace function,
but the performance penalty may be to large (I need it in
a run-time environment, not only in a development
environment).

I have actually started to experiment with an Interceptor
class, whose constructor modifies the __dict__ of a specified
class, to 'wrap' its (callable) instance around the specified
method.

I wanted to make sure, though, that I'm not re-inventing the
wheel, and perhaps hear whether anyone would be interested in
such a package.

So, comments are invited!

Regards,
Fritz
Jul 18 '05 #3
Fritz Bosch wrote:
What I'm looking for is an Interceptor class whose
constructor would interpose its (callable) instance
between a caller and a specified function or method,
and whose 'destroy' method would remove the interposition. I have actually started to experiment with an Interceptor
class, whose constructor modifies the __dict__ of a specified
class, to 'wrap' its (callable) instance around the specified
method. So, comments are invited!


Maybe there isn't such a package because the following is often sufficient:

def wrap(method):
def wrapped(self, *args, **kw):
print "begin"
method(self, *args, **kw)
print "end"
return wrapped
class Test(object):
def method(self, name):
print "method(%r) " % name

t = Test()
t.method("pure" )
Test.method = wrap(Test.metho d)
t.method("wrapp ed")

Peter
Jul 18 '05 #4
I've attached two source fragments which
I had used to wrap/intercept objects.
"weave" can be used to plug between an
object (like a proxy).
It temporarily modifies "self" so that even
method calls inside an object can
be trapped from the outside.
(Sorry could not find a use
case and I'm too lazy to write one
right now.)
The "trace_all" just wraps functions
inside a module.
Well, it probably won't help you much.
But who knows. Maybe you come up with an
idea :-)

Ciao,
Dominic

=============== =============== ===============
=============== =============== ===============

def weave(delegate, into, for_):
class X(object):
def __getattribute_ _(self, key):
def wrapper(*args,* *kargs):
class XX(object):
def __getattribute_ _(self, key):
if getattr(delegat e, key, None):
return getattr(delegat e, key)
else:
return getattr(into, key)
def __setattr__(sel f, key, value):
if getattr(delegat e, key, None):
setattr(delegat e, key, value)
else:
setattr(into, key, value)
return getattr(into.__ class__,key).im _func(XX(), *args, **kargs)
if key in for_: # catch attribute
if getattr(into, key, None): #
return getattr(into, key) #
else:
return wrapper # catch method
elif getattr(delegat e, key, None):
return getattr(delegat e, key)
else:
return getattr(into, key)

def __setattr__(sel f, key, value):
print key, value
setattr(into, key, value)

return X()

=============== =============== ===============
=============== =============== ===============

# wrap stuff here
from trace import trace_all
trace_all('fork ', locals())

---------------------------------

@file ../prototype/trace.py

indent = 0
hash = {}

def trace(name, f):
def wrapper(*args,* *kargs):
"""wrapped" ""
global indent, hash
print " "*indent + "%s:%s(%s,% s)" % (name, f.func_name, args, kargs)
indent = indent + 1
result = f(*args,**kargs )
indent = indent - 1
hash[name] = hash.get(name,{ })
hash[name][f.func_name] = hash[name].get(f.func_nam e,0) + 1
return result
return wrapper

from types import FunctionType

def trace_all(name, d):
for k,v in d.items():
if type(v) == FunctionType and k != 'trace_all' and v.func_doc !=
'wrapped':
#print "Wrap %s" % k
d[k] = trace(name, v)
Jul 18 '05 #5

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

Similar topics

36
6401
by: Andrea Griffini | last post by:
I did it. I proposed python as the main language for our next CAD/CAM software because I think that it has all the potential needed for it. I'm not sure yet if the decision will get through, but something I'll need in this case is some experience-based set of rules about how to use python in this context. For example... is defining readonly attributes in classes worth the hassle ? Does duck-typing scale well in complex
8
2072
by: Georg Brandl | last post by:
Hello c.l.py, what features would you expect of a Python package manager, similar to CPAN or rubygems? I am currently planning to write such a thing, at first privately for myself, and if it's proving useful, I think about releasing it. I plan to model it after gentoo's portage, with less features of course. Would this be acceptable?
0
924
by: oliver.wulff | last post by:
I've developed a framework for ASP.NET with a custom authentication module (HttpModule). This module is already working. This framework should also delegate the authenticated principal automatically therefore the application developer doesn't have to worry about principal delegation. I'm looking for an interceptor mechanism to delegate the principal. I haven't found an outbound interceptor in ASP.NET. I want to set either the authorization...
0
1601
by: | last post by:
Greetings. In an effort to get python2.4 on my Centos 3.7, I installed the python bootstrap rpm. This installed 2.4 alongside 2.2 and updated yum to 2.4.0. Oddly, it didn't create a symlink 'python' for either 2.2 or 2.4. I also get a series of troubling dependency errors when I run yum update. Below is the output of the bootstrap install, which includes both a failure early on (possibly related to alternatives and/or the symlink?)...
4
3383
by: Alia Khouri | last post by:
Can we open up the discussion here about how to improve setuptools which has become the de facto standard for distributing / installing python software. I've been playing around with ruby's gems which seems to be more more mature and usable. From my perspective, the relative immaturity of setuptools and its simultaneous widespread use is a clear python weakness and can make python less easy to absorb than it should be. A few...
0
1922
by: Steven Samuel Cole | last post by:
Hi Stephane, thanks for your reply! :-) I do not get any notification or warning or whatever from dpkg, all output I get when running # sudo dpkg -i python-<package name>_0.0.1-4927-1_all.deb is Selecting previously deselected package python-<package name>. (Reading database ... 15026 files and directories currently installed.)
0
9639
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
9474
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
10308
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...
1
10076
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
9939
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
8964
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...
0
5375
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
5507
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2870
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.