473,804 Members | 3,941 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing parameters using **kargs

I want to access parameters that are passed into a function using the
**kargs idiom. I define f(**kargs) via

def f(**kargs):
print kargs
Jul 18 '05 #1
8 6864
Thomas Philips wrote:
I want to access parameters that are passed into a function using the
**kargs idiom. I define f(**kargs) via

def f(**kargs):
print kargs
.
.

the keyword arguments are converted to a dictionary, so that if I type
f(a=1, b=2, c=3)

the function prints
{'a': 1, 'b': 2, 'c':3}

Now assume the function has three variables a, b and c to which I want
to assign the dictionary's values of 'a', 'b' and 'c'. How can I
assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I
be trying to construct a string representation of each variable's name
and using that as a key, or am I just thinking about this the wrong
way?


How about
def f(a=None, b=None, c=None, **moreargs): .... print locals()
.... f(x=22, b=99) {'moreargs': {'x': 22}, 'a': None, 'c': None, 'b': 99}


Peter
Jul 18 '05 #2
tk****@hotmail. com (Thomas Philips) wrote in
news:b4******** *************** ***@posting.goo gle.com:
I want to access parameters that are passed into a function using the
**kargs idiom. I define f(**kargs) via

def f(**kargs):
print kargs
.
.

the keyword arguments are converted to a dictionary, so that if I type
f(a=1, b=2, c=3)

the function prints
{'a': 1, 'b': 2, 'c':3}

Now assume the function has three variables a, b and c to which I want
to assign the dictionary's values of 'a', 'b' and 'c'. How can I
assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I
be trying to construct a string representation of each variable's name
and using that as a key, or am I just thinking about this the wrong
way?


If the function is to have three variables a, b, and c, then you do this:

def f(a=None, b=None, c=None, **kargs):
... whatever ...

(substitute whatever defaults you want for those variables)

The ** argument is for keyword arguments where you don't know in advance
all the keywords that might be valid. Obviously, if you don't know the name
in advance then there is no point to setting a variable of the same name
since you would have to go through pointless contortions to access it.
If you do know some names of interest in advance then make them arguments
with default values and only use the ** form for the remaining arguments.
Jul 18 '05 #3

"Duncan Booth"
Thomas Philips) >
I want to access parameters that are passed into a function using the
**kargs idiom. I define f(**kargs) via

def f(**kargs):
print kargs
The ** argument is for keyword arguments where you don't know in advance
all the keywords that might be valid.


Or if you don't care, or want to intercept invalid calls. Interestingly,
the OP's example is the beginning of a possible debug wrapper usage where
one either does not have a function's code or does not want to modify it
directly. Possible example:

_f_orig = f
def f(*largs, **kargs):
print 'f called with' largs, 'and', kargs
f(*largs, **kargs)

Terry J. Reedy


Jul 18 '05 #4
tk****@hotmail. com (Thomas Philips) wrote in message news:<b4******* *************** ****@posting.go ogle.com>...
I want to access parameters that are passed into a function using the
**kargs idiom. I define f(**kargs) via

def f(**kargs):
print kargs
.
.

the keyword arguments are converted to a dictionary, so that if I type
f(a=1, b=2, c=3)

the function prints
{'a': 1, 'b': 2, 'c':3}

Now assume the function has three variables a, b and c to which I want
to assign the dictionary's values of 'a', 'b' and 'c'. How can I
assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I
be trying to construct a string representation of each variable's name
and using that as a key, or am I just thinking about this the wrong
way?

Thomas Philips


MY reading of what you say is - I have three variable a, b and c.. and
a dictionary, kargs, with keys 'a', 'b' anc 'c'. I want to assign the
contents of kargs to the three variables. The specific case is surely
? :
a = kargs['a']
b = kargs['b']
c = kargs['c']

or is it the more general case you're after ?
I think I'm misunderstandin g you I'm afraid....

Fuzzyman

http://www.voidspace.org.uk/atlantib...thonutils.html
Jul 18 '05 #5
Since kargs is a regular dictionary variable,
you can reference the variables you want with
kargs.get('<var iablename>', None)

example

kargs.get('a', None) will return value of
keyword argument a or None if 'a' doesn't
exist.

If you are sure of what will exist you can just
use kargs['a'], but then you could more easily
do f(a=None, **kargs) in that case.

kargs.keys() will give you the names of the
keyword arguments if you want them.

No real reason to put them anywhere else that I
can see.

HTH,
Larry Bates

"Thomas Philips" <tk****@hotmail .com> wrote in message
news:b4******** *************** ***@posting.goo gle.com...
I want to access parameters that are passed into a function using the
**kargs idiom. I define f(**kargs) via

def f(**kargs):
print kargs
.
.

the keyword arguments are converted to a dictionary, so that if I type
f(a=1, b=2, c=3)

the function prints
{'a': 1, 'b': 2, 'c':3}

Now assume the function has three variables a, b and c to which I want
to assign the dictionary's values of 'a', 'b' and 'c'. How can I
assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I
be trying to construct a string representation of each variable's name
and using that as a key, or am I just thinking about this the wrong
way?

Thomas Philips

Jul 18 '05 #6
In article <b4************ **************@ posting.google. com>,
tk****@hotmail. com (Thomas Philips) wrote:
I want to access parameters that are passed into a function using the
**kargs idiom. I define f(**kargs) via

def f(**kargs):
print kargs
.
.

the keyword arguments are converted to a dictionary, so that if I type
f(a=1, b=2, c=3)

the function prints
{'a': 1, 'b': 2, 'c':3}

Now assume the function has three variables a, b and c to which I want
to assign the dictionary's values of 'a', 'b' and 'c'. How can I
assign kargs['a'] to a, kargs['b'] to b, and kargs['c'] to c. Should I
be trying to construct a string representation of each variable's name
and using that as a key, or am I just thinking about this the wrong
way?


I don't understand. Isn't this it:

Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright" , "credits" or "license" for more information.
kargs={'a':1, 'b':2, 'c':3}
def r(a, b, c): .... print a, b, c
.... r(**kargs)

1 2 3
Use of keyword arguments doesn't NEED to be part of the
function definition.

Regards. Mel.
Jul 18 '05 #7
In article <ma************ *************** **********@pyth on.org>,
Terry Reedy <tj*****@udel.e du> wrote:

Or if you don't care, or want to intercept invalid calls. Interestingly,
the OP's example is the beginning of a possible debug wrapper usage where
one either does not have a function's code or does not want to modify it
directly. Possible example:

_f_orig = f
def f(*largs, **kargs):
print 'f called with' largs, 'and', kargs
f(*largs, **kargs)


You mean

_f_orig(*largs, **kargs)

I prefer this version:

def debugParams(fun c):
def debugger(*args, **kwargs):
for arg in args:
print type(arg), arg
for name in kwargs:
value = kwargs[name]
print name, type(value), value
return func(*args, **kwargs)
return debugger

f = debugParams(f)
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
Jul 18 '05 #8

"Aahz" <aa**@pythoncra ft.com> wrote in message
news:ca******** **@panix1.panix .com...
_f_orig = f
def f(*largs, **kargs):
print 'f called with' largs, 'and', kargs
f(*largs, **kargs)
You mean

_f_orig(*largs, **kargs)


Of course. Silly 'rushing out the door' mistake.
I prefer this version:

def debugParams(fun c):
def debugger(*args, **kwargs):
for arg in args:
print type(arg), arg
for name in kwargs:
value = kwargs[name]
print name, type(value), value
return func(*args, **kwargs)
return debugger

f = debugParams(f)


So do I, for its elaboration, factorization, and closure. I am saving it.

Terry J. Reedy


Jul 18 '05 #9

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

Similar topics

2
1446
by: Edward C. Jones | last post by:
Here is a stripped-down version of a Python Cookbook recipe. Is there a simpler, more Pythonical, natural way of doing this? ------ #! /usr/bin/env python # Modified from Python Cookbook entry 91192, "eiffelmethod" by Andres # Tuells. The url is # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/91192
2
17361
by: zlatko | last post by:
There is a form in an Access Project (.adp, Access front end with SQL Server) for entering data into a table for temporary storing. Then, by clicking a botton, several action stored procedures (update, append) should be activated in order to transfer data to other tables. I tried to avoid any coding in VB, as I am not a professional, but I have found a statement in an article, that, unlike select queries, form's Input Property can't be...
3
14960
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
12
2811
by: Joel | last post by:
Hi all, Forgive me if I've expressed the subject line ill. What I'm trying to do is to call a c++ function given the following: a. A function name. This would be used to fetch a list of function descriptors for the overloaded functions of that name. A function descriptor would contain the address of the function to be called, and a description of the parameters that it must take. b. A list of parameters. This would be compared to the...
7
2872
by: Harolds | last post by:
The code below worked in VS 2003 & dotnet framework 1.1 but now in VS 2005 the pmID is evaluated to "" instead of what the value is set to: .... xmlItems.Document = pmXML // Add the pmID parameter to the XSLT stylesheet XsltArgumentList xsltArgList = new XsltArgumentList(); xsltArgList.AddParam("pmID", "", pmID); xmlItems.TransformArgumentList = xsltArgList;
17
3607
by: Charles Sullivan | last post by:
The library function 'qsort' is declared thus: void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *)); If in my code I write: int cmp_fcn(...); int (*fcmp)() = &cmp_fcn; qsort(..., fcmp); then everything works. But if instead I code qsort as:
8
4416
by: Johnny | last post by:
I'm a rookie at C# and OO so please don't laugh! I have a form (fclsTaxCalculator) that contains a text box (tboxZipCode) containing a zip code. The user can enter a zip code in the text box and click a button to determine whether the zip code is unique. If the zip code is not unique, another form/dialog is displayed (fclsLookup) - lookup form/dialog. The zip code is passed to the lookup form/dialog by reference. I then load a...
4
3852
by: Nathan Sokalski | last post by:
I am a beginner with AJAX, and have managed to learn how to use it when passing single parameters, but I want to return more than one value to the client-side JavaScript function that displays it. My client-side JavaScript function takes 4 parameters (which are expected to be integers). The idea of passing a single parameter and parsing it on the client has occurred to me, but since I am sure I am not the only person who has situations that...
2
4439
by: luis | last post by:
I'm using ctypes to call a fortran dll from python. I have no problems passing integer and double arryas, but I have an error with str arrys. For example: ..... StringVector = c_char_p * len(id) # id is a list of strings Id_dat=StringVector() for i in range(len(Id)): ....Id_dat=id
0
9706
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
9584
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
10337
jinu1996
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...
1
10323
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
10082
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...
1
7622
isladogs
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...
0
5525
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...
1
4301
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3822
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.