Parsing functions(?)
Hans Nowak
hnowak at cuci.nl
Thu Dec 9 16:12:50 EST 1999
On 9 Dec 99, at 15:32, Paul M wrote:
> Dear Pythoneers,
>
> I'd like to write a "function recorder" class, something like this:
>
> class frecorder:
> def __init__(self):
> self.flist = []
>
> def record(self, fxncall):
> fxn, arg = **UNKNOWN**(fxncall)
> self.flist.append((fxn,arg))
>
> Object of this hypothetical class could then be used to build up a
> record of function calls and arguments which could then be applied all at
> one time, something like the following:
>
> >>> rec = frecorder()
> >>> rec.record(foo(1))
AFAIK, this will pass the *result* of function call foo(1) to the
method, which has no way of figuring out which how that value was
obtained.
> >>> rec.record(bar('string', (t1,t2))
> >>> rec.flist
> [(function foo at XXXX, (1,)), (function bar at XXXX, ('string',
> (t1,t2))]
> >>> for i in rec.flist:
> apply(i[0], i[1])
>
> etc....
>
> I know I could instead define the record method like this:
>
> def record(self, fname, fargs):
> self.flist.append((fname, fargs))
>
> which would be called like:
> rec.record(foo, (1,))
>
> but it doesn't seem as natural as the first example, and besides it
> means that one has to remember to do thinks like specify 1-tuples when the
> function only takes a single argument.
Still, this is the way to go. If you worry about those tuples, try
this approach instead:
# recorder.py
class frecorder:
def __init__(self):
self.flist = []
def record(self, func, *args):
self.flist.append(func, args)
def twice(x): return x*2
rec = frecorder()
rec.record(id, twice) # one arg
rec.record(map, twice, [1,2,3]) # two args
rec.record(hex, 78)
rec.record(locals) # no args
print rec.flist
for func, args in rec.flist:
print func, '->', args # show function and args
print apply(func, args) # show result
#----end of code------
You can call rec.record with the function as the first argument,
followed by optional second, third, etc. arguments which are the
arguments for a call of that function. See the example above.
HTH,
--Hans Nowak (zephyrfalcon at hvision.nl)
Homepage: http://fly.to/zephyrfalcon
You call me a masterless man. You are wrong. I am my own master.
More information about the Python-list
mailing list