Tuple passed to function recognised as string

R. David Murray rdmurray at bitdance.com
Thu Mar 19 01:12:02 CET 2009


Mike314 <michaelst at gmail.com> wrote:
> Hello,
> 
>    I have following code:
> 
> def test_func(val):
>     print type(val)
> 
> test_func(val=('val1'))
> test_func(val=('val1', 'val2'))
> 
> The output is quite different:
> 
> <type 'str'>
> <type 'tuple'>
> 
> Why I have string in the first case?

Because in Python the syntactic element that defines something
as a tuple is the comma, not the parenthesis:

>>> x = 1, 2
>>> type(x)
<type 'tuple'>
>>> y = (1,)
>>> type(y)
<type 'tuple'>
>>> z = 1,
>>> type(z)
<type 'tuple'>

In your function call the comma would normally be an argument
separator, so in that context you do need the parenthesis as well:

test_func(val=('val1',))

--
R. David Murray           http://www.bitdance.com




More information about the Python-list mailing list