*args question

Tim Chase python.list at tim.thechases.com
Wed Mar 25 16:28:27 CET 2009


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).

-tkc







More information about the Python-list mailing list