*args question
grocery_stocker
cdalten at gmail.com
Wed Mar 25 11:46:27 EDT 2009
On Mar 25, 8:28 am, Tim Chase <python.l... at tim.thechases.com> wrote:
> grocery_stocker wrote:
> > On Mar 25, 7:05 am, grocery_stocker <cdal... at gmail.com> wrote:
> >> Given the following code...
>
> >> #!/usr/bin/env python
>
> >> import time
> >> import thread
>
> >> def myfunction(string,sleeptime,*args):
> >> while 1:
>
> >> print string
> >> time.sleep(sleeptime) #sleep for a specified amount of time.
>
> >> if __name__=="__main__":
>
> >> thread.start_new_thread(myfunction,("Thread No:1",2))
>
> >> while 1:pass
>
> >> Taken from following URL....http://linuxgazette.net/107/pai.html
>
> >> How can myfunction() extract the tuple ("Thread No:1",2) from
> >> start_new_thread() if myfunction is only being passed the single arg
> >> ("Thread No:1",2)
>
> > The only thing that I think of is that the tuple ("Thread No:1",2) is
> > somehow being extract before it gets passed to myfunction(). Ie,
> > something like the following...
>
> > [cdalten at localhost ~]$ python
> > Python 2.4.3 (#1, Oct 1 2006, 18:00:19)
> > [GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
> >>>> def myfunction(first, second, *args):
> > ... print "The formal args are: ", args
> > ... print "the first value is:", first
> > ... print "the second value is:", second
> > ...
> >>>> a, b = (1,2)
> >>>> myfunction(a,b)
> > The formal args are: ()
> > the first value is: 1
> > the second value is: 2
>
> and if you call "myfunction(1,2,("Thread No:1",2))", you should
> get something like
>
> The formal args are: (('Thread No:1', 2),)
> the first value is: 1
> the second value is: 2
>
> It's a list of the various items you put in:
>
> def show_args(first, second, *args):
> print "first", first
> print "second", second
> for i, arg in enumerate(args):
> print "#%i %s" % (i, arg)
>
> So you can either access "args[0]" (which is a bit dangerous, as
> you assume there may be a value when there's not), or you can do
> the more traditional thing of just treating it like a list as
> above (e.g. iterating over it or using it in a list-comprehension).
>
Maybe I'm missing it, but in the original code, the line had
thread.start_new_thread(myfunction,("Thread No:1",2))
It has a single arg ("Thread No:1",2) versus something like
thread.start_new_thread(myfunction,1, 2, ("Thread No:1",2))
But
def myfunction(string,sleeptime,*args):
clearly takes two args. I don't get how the single arg ("Thread No:1",
2) in start_new_thread() gets magically converted two arges, string
and sleeptime, before it reaches myfunction().
More information about the Python-list
mailing list