473,289 Members | 1,840 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

generic function that calls others

I want to write a generic function that calls other functions and does some additional pre and post processing.

Example calls:

genericfn(function=max,a=3,b=4) would call max(a=3,b=4) and return 4
genericfn(function=average,a=4,c=8) would call average(a=4,c=8) and return 6, assuming parameter b in fn average defaults to 6

It should handle any user-defined function with a variable number of keyword args.
Here's the code I have so far, but I don't know how to get the dictionary to convert to a series of keyword args.

def genericfn(*args,**kwargs):
fnToApply = kwargs['function']
del kwargs['function']
return fnToApply(args,kwargs)

Thanks for your help.
Oct 22 '07 #1
2 1700
bvdet
2,851 Expert Mod 2GB
I want to write a generic function that calls other functions and does some additional pre and post processing.

Example calls:

genericfn(function=max,a=3,b=4) would call max(a=3,b=4) and return 4
genericfn(function=average,a=4,c=8) would call average(a=4,c=8) and return 6, assuming parameter b in fn average defaults to 6

It should handle any user-defined function with a variable number of keyword args.
Here's the code I have so far, but I don't know how to get the dictionary to convert to a series of keyword args.

def genericfn(*args,**kwargs):
fnToApply = kwargs['function']
del kwargs['function']
return fnToApply(args,kwargs)

Thanks for your help.
Something like this:
Expand|Select|Wrap|Line Numbers
  1. import operator
  2.  
  3. def genericfn(*args,**kwargs):
  4.     fnToApply = kwargs['function']
  5.     del kwargs['function']
  6.     return fnToApply(*args)
  7.  
  8. dd = {'function': max}
  9. print genericfn(1,2,3,4,5,**dd)
  10.  
  11. dd = {'function': operator.mul}
  12. print genericfn(7,9,**dd)
>>> 5
63
>>>
Oct 23 '07 #2
elcron
43
Expand|Select|Wrap|Line Numbers
  1. def someFunction(*args, **kwargs):
  2.     "someFunction"
  3.     print 'args:   ',args
  4.     print 'kwargs: ',kwargs
  5.  
  6. def factoryFunction(func, *args, **kwargs):
  7.     print 'Starting %s'%func.__doc__  # code before
  8.     values = func(*args, **kwargs)
  9.     print 'Finishing %s'%func.__doc__ # code after
  10.     return values
  11.  
  12. >>> factoryFunction(someFunction, 1,2,3,['a','list'], greeting='hello', number=1)
  13. Starting someFunction
  14. args:    (1, 2, 3, ['a', 'list'])
  15. kwargs:  {'greeting': 'hello', 'number': 1}
  16. Finishing someFunction
  17.  
  18. >>> args = (someFunction, 1,2,3,['a','list'])
  19. >>> kwargs = {'greeting':'hello', 'number':1}
  20. >>> factoryFunction(*args, **kwargs)
  21. Starting someFunction
  22. args:    (1, 2, 3, ['a', 'list'])
  23. kwargs:  {'greeting': 'hello', 'number': 1}
  24. Finishing someFunction
  25.  
'*' creates a tuple of all extra the values and '*' can also turn a tuple back into arguments
'**' creates a dictionary of all the extra keywords and '**' can also turn a dictionary back into keywords
I would recommend requiring the function be passed in and save yourself the trouble of having to extract and remove it.
Oct 23 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

35
by: Gabriel Zachmann | last post by:
Is there any generic way to use C++ libraries from within Python. I seem to recall that there are tools to generate wrappers for C-libraries semi-automatically. But those were still way too...
17
by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the...
3
by: .Net Newbie | last post by:
I'm new to .Net and need to create a generic (free) way to update lookup tables in SQL Server (using C#) in ASP.Net pages. I found an article at:...
6
by: Urs Eichmann | last post by:
While experimenting with the Feb CTP Edition of VB 2005, I came across "generic procedures". You can write: Public Class Foo Public Sub MySub(Of tDisp As IDisposable)(ByVal vMyParm As Integer)...
5
by: Anders Borum | last post by:
Hello! Whilst refactoring an application, I was looking at optimizing a ModelFactory with generics. Unfortunately, the business objects created by the ModelFactory doesn't provide public...
2
by: Greg Buchholz | last post by:
/* I've been experimenting with some generic/polytypic programs, and I've stumbled on to a problem that I can't quite figure out. In the program below, I'm trying to define a generic version of...
16
by: tshad | last post by:
This is a little complicated to explain but I have some web services on a machine that work great. The problem is that I have run into a situation where I need to set up my program to access one...
4
by: Charles Churchill | last post by:
I apologize if this question has been asked before, but after about half an hour of searching I haven't been able to find an answer online. My code is beloiw, with comments pertaining to my...
1
by: Noah Roberts | last post by:
I need to create a log file that logs calls to a certain API. The obvious way to do this is to put a bunch of output functions before/after calls but it seems to me that there should be a generic...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.