[Tutor] checking for expected types from input file

John Fouhy john at fouhy.net
Thu Jul 31 05:05:00 CEST 2008

On 31/07/2008, Bryan Fodness <bryan.fodness at gmail.com> wrote:
> I am populating a dictionary from an input file, and would like to create an
> error code if a string is sent to a variable that expects a float or int.
> INPUT = {}
> for line in open(infile):
>     input_line = line.split(' = ')
>     INPUT[input_line[0].strip()] = input_line[1].strip()
> if INPUT.has_key('ReferencePositionX'):
>     refx = float(INPUT['ReferencePositionX'])/10
>      refy = float(INPUT['ReferencePositionY'])/10
>     refz = float(INPUT['ReferencePositionZ'])/10
> I have many variables of different types, and I want to do a check in case
> something like ReferencePositionX = abc occurs.

You could make a dictionary that contains the types you expect; e.g.:

variable_types = { 'ReferencePositionX':float,
'ReferencePositionY':float, 'NumberOfWidgets':int, 'MyFirstName':str }

Then when you're reading in your data:

INPUT = {}
for line in open(infile):
    input_line = line.split(' = ')
    var_name = input_line[0].strip()
    INPUT[var_name] = variable_types[var_name](input_line[1].strip())

This means that:

1. Your INPUT dictionary will have all the values as the right types
(floats will be floats, not strings like '123.4', etc).
2. If you meet a variable name you're not expecting, the code will
raise a KeyError which may alert you to broken data, or which you can
catch and deal with.
3. If a variable has a bad value (like a string where it should have a
float), the code will raise a ValueError, which again will alert you
to a problem.
(note that str() works on everything, and int() works on floats and
vice versa, so if you want to be really picky, you will need to write
your own validation functions)


More information about the Tutor mailing list