one-element tuples

Martin A. Brown martin at linux-ip.net
Sun Apr 10 21:08:02 EDT 2016


Hello Fillmore,

> Here you go:
>
> >>> a = '"string1"'
> >>> b = '"string1","string2"'
> >>> c = '"string1","string2","string3"'
> >>> ea = eval(a)
> >>> eb = eval(b)
> >>> ec = eval(c)
> >>> type(ea)
> <class 'str'>   <--- HERE !!!!
> >>> type(eb)
> <class 'tuple'>
> >>> type(ec)
> <class 'tuple'>
>
> I can tell you that it exists because it bit me in the butt today...
>
> and mind you, I am not saying that this is wrong. I'm just saying 
> that it surprised me.

Recently in one of these two threads on your question, people have 
identified why the behaviour is as it is.

Below, I will add one question (about eval) and one suggestion about 
how to circumvent the behaviour you perceive as a language 
discontinuity.

#1: I would not choose eval() except when there is no other 
    solution.  If you don't need eval(), it may save you some 
    headache in the future, as well, to find an alternate way.
    So, can we help you choose something other than eval()?
    What are you trying to do with that usage?

#2: Yes, but, you can outsmart Python here!  Simply include a 
    terminal comma in each case, right?  In short, you can force
    the consuming language (Python, because you are calling eval())
    to understand the string as a tuple of strings, rather than 
    merely one string.

    >>> a = '"string1",'
    >>> ea = eval(a)
    >>> len(ea), type(ea)
    (1, <type 'tuple'>)

    >>> b = '"string1","string2",'
    >>> eb = eval(b)
    >>> len(eb), type(eb)
    (2, <type 'tuple'>)

    >>> c = '"string1","string2","string3",'
    >>> ec = eval(c)
    >>> len(ec), type(ec)
    (3, <type 'tuple'>)

Good luck in your continuing Python explorations,

-Martin

P.S. Where do your double-quoted strings come from, anyway?

-- 
Martin A. Brown
http://linux-ip.net/



More information about the Python-list mailing list