I want to write a generic function that calls other functions and does some additional pre and post processing.
Example calls:
genericfn(funct ion=max,a=3,b=4 ) would call max(a=3,b=4) and return 4
genericfn(funct ion=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.
2 1709 bvdet 2,851
Recognized Expert Moderator Specialist
I want to write a generic function that calls other functions and does some additional pre and post processing.
Example calls:
genericfn(funct ion=max,a=3,b=4 ) would call max(a=3,b=4) and return 4
genericfn(funct ion=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: - import operator
-
-
def genericfn(*args,**kwargs):
-
fnToApply = kwargs['function']
-
del kwargs['function']
-
return fnToApply(*args)
-
-
dd = {'function': max}
-
print genericfn(1,2,3,4,5,**dd)
-
-
dd = {'function': operator.mul}
-
print genericfn(7,9,**dd)
>>> 5
63
>>>
-
def someFunction(*args, **kwargs):
-
"someFunction"
-
print 'args: ',args
-
print 'kwargs: ',kwargs
-
-
def factoryFunction(func, *args, **kwargs):
-
print 'Starting %s'%func.__doc__ # code before
-
values = func(*args, **kwargs)
-
print 'Finishing %s'%func.__doc__ # code after
-
return values
-
-
>>> factoryFunction(someFunction, 1,2,3,['a','list'], greeting='hello', number=1)
-
Starting someFunction
-
args: (1, 2, 3, ['a', 'list'])
-
kwargs: {'greeting': 'hello', 'number': 1}
-
Finishing someFunction
-
-
>>> args = (someFunction, 1,2,3,['a','list'])
-
>>> kwargs = {'greeting':'hello', 'number':1}
-
>>> factoryFunction(*args, **kwargs)
-
Starting someFunction
-
args: (1, 2, 3, ['a', 'list'])
-
kwargs: {'greeting': 'hello', 'number': 1}
-
Finishing someFunction
-
' *' 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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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 cumbersome, IMHO.
What I would like to have is some module (or whatever), with which I can
say "load this C++ library", and then, "create that C++ object" or "call
method x of C++ object y".
|
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 way they
are.
***** Summary & Questions *****
In a nutshell, the current .NET generics & .NET framework make it
sometimes difficult or even impossible to write truly generic code.
For example, it seems to be impossible to write a truly generic
|
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:
http://www.dotnetjunkies.com/Tutorial/0C968B48-44E8-4637-9F19-8490B0429881.dcik
which explains how this can be done but does not supply enough example code
my newbie self to go through in detail where I understand it. So, does
anyone have some example code I could use to accomplish this or know...
|
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)
End Sub
|
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 constructors (because we do not
allow developers to instantiate them directly).
Because our business objects are instantiated very frequently, the idea of
using reflection sounds like a performance killer (I haven't done any tests
on this, but the...
| |
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 "transform"
which works not only on lists, but lists of list, lists of lists of
lists, etc. I'm calling it "fmap" and it passes around actual lists
instead of iterators (for now). In order to get it to work, I thought
I'd have one templated...
|
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 or another (could also be 3) different web servers to
use these Web Services. The Web Services are identical on all the machines.
I tried just changing the URL of the Web Services and cannot make it work.
I then decided to create 2 identical web...
|
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 question
In short my question is why when I pass a generic type directly to the
formatObject function it works fine, but when I pass it to the
checkText function where it is itself a generic argument, and then it
is passed to formatObject, it is seen...
|
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
way to do this. Perhaps some way to override or use boost::function so
that you just wrap up your function in one of these function logging
objects and then invoke it...it does the rest. That is the kind of
thing I am looking for.
Anyone got...
|
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,...
|
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...
| |
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...
|
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,...
|
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...
|
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...
|
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();...
|
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...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |