Emulating Pascal input

Carel Fellinger carel.fellinger at iae.nl
Thu May 23 20:58:26 EDT 2002


On Thu, May 23, 2002 at 08:33:19PM +0000, Bengt Richter wrote:
...snipped problem statement
> ISTM the key problem is that you are asking for type-driven input,
> but not wanting to tell Python about it explicitly. You visualize
> typed Pascal variables being filled with numeric values taken from
> an input character sequence according to their type, but a Python
> 'variable' is just a name. There is no static type associated with
> a name. You have to go to the value object it refers to to get any

Right, so the only solution is to supply the needed info:) Pascal does
this by typing vars, in Python one can't do the same, but if you're
willing to list the types you want to the readln function, you can
hide most of the perceived ugliness. like:

   >>> def readln(from, *types, seperator=None):
   ...   for t,s in zip(types, from.readline(seperator).split()):
   ...       yield  t(s)
   ...
   >>> readln(sys.stdin, int, int, seperator=",")
   123, 12
   [123, 12]
   >>> readln(sys.stdin, int, int)
   123 12
   [123, 12]
   >>> readln(sys.stdin, int, float)
   123 12
   [123, 12.0]

Ofcourse the above readln is minimalistic, but it's easy to enhance it:

   def readln(from, *types, seperator=None):
       line = from.readline()
       for t in types:
           try:
                yield line[:t]
                line = line[t:]
           except TypeError:
              line = line.split(seperator, 1)
              v, line = line[0], (line[1:] or [""])[0]
              yield t(v)


now you can even read fixed lengths strings:)

   >>> readln(sys.stdin, 4, float)
   12 21
   ['12 2', 1.0]


ofcourse the above funtion still needs a lot of work, especially if
you want to mimic Pascal's willingness to read more then one line
whilst scanning for integer's and/or real's.






More information about the Python-list mailing list