force sequenz with only one item?

Gordon McMillan gmcm at hypernet.com
Sun Jun 13 02:45:43 CEST 1999


Holger Jannsen asks:
> 
> I think it's easy to solve, but I couldn't get it right now.
> Take a look at the command-line source below:
> 
> >>> A = 0
> >>> B = 1
> >>> seq=raw_input("?")
> ?A,B
> >>> print seq
> A,B
> >>> print eval(seq)
> (0, 1)
> >>> seq=raw_input("?")
> ?A
> >>> print eval(seq)
> 0
> >>> A in seq
> Traceback (innermost last)
:...
> TypeError: 'in' or 'not in' needs sequence right argument
> >>>

The reason "A,B" gets evaluated to the sequence (0,1) is because of 
the comma. "(A,)" would get evaluated to (0,), while "[A]" would 
evaluate to [0]. If you want to always end up with sequences, you 
should probably eval it and test it:

  if type(evaledinput) not in (type(()), type([])):
      evaledinput = (evaledinput,)

Single element tuples need the extra comma to distinguish them from
a simple grouping, as in  4 * ( 3 + 7 ). It would cause great
wailing and gnashing of teeth if it yeilded (10, 10, 10, 10).

even-worse-than-while-1-ly y'rs

- Gordon




More information about the Python-list mailing list