[Tutor] dynamic argument lists

Bob Gailer bgailer at gmail.com
Fri Aug 29 19:02:12 CEST 2008


On Fri, Aug 29, 2008 at 12:20 PM, Kent Johnson <kent37 at tds.net> wrote:

> On Fri, Aug 29, 2008 at 9:49 AM, eShopping
> <etrade.griffiths at dsl.pipex.com> wrote:
> > Hi
> >
> > I have a GUI program that extracts some information from the user as
> > strings, and I then want to use the strings to form an argument list to
> > another function.  Hopefully the following code gives some flavour:
> >
> > def myfunc(**kwargs):
> >    while kwargs:
> >        name, value = kwargs.popitem()
> >        print name, value
> >
> > myfunc(a=1, b=2, c=3, d=4)
> > arg_str = "a=1, b=2, c=3, d=4"
> > myfunc(arg_str)
> >
> > ARG_STR will be built up from the data extracted from the GUI.  I get
> this
> > error
> >
> > TypeError: myfunc() takes exactly 0 arguments (1 given)
> >
> > I understand that ARG_STR is a string and that MYFUNC is expecting
> something
> > else ,,, but not sure what it is.  I have tried various dictionary
> > configurations such as
> >
> > arg1 = ["a","b","c","d"]
> > arg2 = [1,2,3,4]
> > arg3 = dict(zip(arg1,arg2))
> > myfunc(arg3)
>

 myfunc(**arg3)

Let's back up to arg_str = "a=1, b=2, c=3, d=4"

To create a dictionary from that:

argDict = dict(pair.split('=') for pair in arg_str.split(','))

If there is no compelling requirement that myfunc's argument be in the form
**kwargs then

def myfunc(kwargs):
    while kwargs:
        name, value = kwargs.popitem()
        print name, value

myfunc(argDict)

-- 
Bob Gailer
919-636-4239
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080829/9ed3dc21/attachment-0002.htm>


More information about the Tutor mailing list