Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Printing the arguments of an attribute in a class

1 view
Skip to first unread message

vsoler

unread,
Feb 28, 2010, 9:42:00 AM2/28/10
to
I have a class that is a wrapper:

class wrapper:
def __init__(self, object):
self.wrapped = object
def __getattr__(self, attrname):
print 'Trace: ', attrname
#print arguments to attrname, how?
return getattr(self.wrapped, attrname)

I can run it this way:

>>> x = wrapper([1,2,3])
>>> x.append(4)
Trace: append
>>> x.wrapped
[1, 2, 3, 4]

I am able to capture the attribute name to x (that is, append).
However, I do not know how to capture and print all of its arguments
(in this case number 4).

How should I proceed?

Thank you

Alf P. Steinbach

unread,
Feb 28, 2010, 10:00:19 AM2/28/10
to
* vsoler:

If your goal is just learning then in your __getattr__ you might return a
wrapper for the attribute instead of the attribute itself. Equip the wrapper
with a __call__ method if it is a method. And equip it with other special
methods as appropriate.

I can imagine that that approach will lead to some practical problems, but it
may be great for learning.

If your goal is tracing, then I suggest looking at the "trace" module.

If your goal is something else purely practical, like intercepting method calls
to do arbitrary things (logging, marshaling, whatever) then I suspect that it
might getspretty complicated, hairy. For specific method calls you might just
use subclassing, but for doing this in general, parameterized, you'd need to
about the same kinds of things as the trace module does. So I guess then one
idea might be to look at the source code of that module.

But if that's what you intend to do, then best check first if there is an
existing solution. ParcPlace did this thing for a number of languages and
introduced a special term for it, I can't recall but something like
"cross-whatever mumbo jumbo concerns" plus one single catchy name. There might
be an existing Python implementation.


Cheers & hth.,

- Alf

vsoler

unread,
Feb 28, 2010, 10:31:30 AM2/28/10
to

Alf,

My goal is just learning. In the code provided in the post I just
can't think of a method to "see", "capture" or "use" the parameters. I
am going to study the __call__ method and see if I can figure out how
I can capture the parameters.

Thank you Alf

Arnaud Delobelle

unread,
Feb 28, 2010, 12:51:44 PM2/28/10
to
vsoler <vicent...@gmail.com> writes:

You could do something like this:

class wrapper:
def __init__(self, object):
self.wrapped = object
def __getattr__(self, attrname):

print '** get attribute: ', self.wrapped, attrname
return wrapper(getattr(self.wrapped, attrname))
def __call__(self, *args, **kwargs):
print '** call with args: ', self.wrapped, args, kwargs
return wrapper(self.wrapped(*args, **kwargs))

x = wrapper([1,2,3])
x.append(4)

I haven't thought about it too much though.

--
Arnaud

0 new messages