Why does passing tuple as arg WITHOUT scattering work?

Alf P. Steinbach alfps at start.no
Tue Oct 20 18:30:29 EDT 2009


* Rhodri James:
> On Tue, 20 Oct 2009 22:42:07 +0100, Alf P. Steinbach <alfps at start.no> 
> wrote:
> 
> [snip]
> 
>> canvas.create_oval( bbox, fill = "PeachPuff" )
> 
> [snip]
> 
>> It worked nicely, and I thought this code was fairly perfect until I 
>> started studying the language reference.
>>
>> It seems that formally correct code should apply the scatter operator 
>> to the tuple, like this:
>>
>>
>> canvas.create_oval( *bbox, fill = "PeachPuff" )
>>
>>
>> And this /also/ works nicely!
>>
>> I think it's this latter that is correct, and that the former just 
>> worked by accident, due to e.g. the way that some C function parses 
>> arguments or such?
>>
>> But I'm unable to figure it out, so, what's correct (both? one?), and 
>> assuming it's the latter that's correct, would the first version still 
>> work in practice regardless of Python / Tkinter implementation?
> 
> No.  Tkinter.py goes to some lengths to make both of these work, unpacking
> bbox if it happens to be a tuple (or packing if it wasn't; I admit I
> didn't look at Tkinter.py very hard!)

Thanks, I now just found this code in [Tkinter.py]

<code>
     def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
         """Internal function."""
         args = _flatten(args)
         cnf = args[-1]
         if type(cnf) in (DictionaryType, TupleType):
             args = args[:-1]
         else:
             cnf = {}
         return getint(self.tk.call(
             self._w, 'create', itemType,
             *(args + self._options(cnf, kw))))
</code>

and although I don't understand it all it seems indeed to deal specially with a 
dictionary or tuple as argument.

However I didn't find that documented anywhere.

I guess I'll find that sooner or later... :-)


> As to which of the approaches is correct, the answer is whichever one
> works for a given function.  It's rare to see the second version, partly
> because it's rare to have a tuple in hand that you want to unpack like
> that if you don't need to.  However, generally speaking a function will
> expect a tuple or not; libraries that can cope with either are the
> exception rather than the rule.


Cheers & thanks again, that cleared it up,

- Alf



More information about the Python-list mailing list