Automatic string to numeric type conversion

Sun, 01 Aug 2010 15:56:33 +0200

author
Andy Buckley <andy@insectnation.org>
date
Sun, 01 Aug 2010 15:56:33 +0200
changeset 4
ff16e3d891cd
parent 3
d52a5a633a6c
child 5
825fed016ac1

Automatic string to numeric type conversion

pyslha.py file | annotate | diff | comparison | revisions
     1.1 --- a/pyslha.py	Sun Aug 01 01:14:45 2010 +0200
     1.2 +++ b/pyslha.py	Sun Aug 01 15:56:33 2010 +0200
     1.3 @@ -2,6 +2,18 @@
     1.4  
     1.5  import re
     1.6  
     1.7 +def _autotype(var):
     1.8 +    if type(var) != str:
     1.9 +        return var
    1.10 +    if var.isdigit():
    1.11 +        return int(var)
    1.12 +    try:
    1.13 +        f = float(var)
    1.14 +        return f
    1.15 +    except ValueError:
    1.16 +        return var
    1.17 +
    1.18 +
    1.19  class Block:
    1.20      def __init__(self, name):
    1.21          self.name = name
    1.22 @@ -12,6 +24,9 @@
    1.23          nextparent = self.entries
    1.24          if len(entry) < 2:
    1.25              raise Exception("Block entries must be at least a 2-tuple")
    1.26 +        #print "in", entry
    1.27 +        entry = map(_autotype, entry)
    1.28 +        #print "out", entry
    1.29          for e in entry[:-2]:
    1.30              if e is not entry[-1]:
    1.31                  nextparent = nextparent.setdefault(e, {})
    1.32 @@ -81,4 +96,4 @@
    1.33          #     print b
    1.34          #     print
    1.35  
    1.36 -        print blocks["MASS"].entries["25"]
    1.37 +        print blocks["MASS"].entries[25]

mercurial