DISPATCH
fpy.py
1 """Conversion of Fortran values (as strings) to equivalent Python values.
2 
3 The functions in this module are used to convert the string representation of
4 the values of basic Fortran data types into equivalent Python values.
5 
6 :copyright: Copyright 2014 Marshall Ward, see AUTHORS for details.
7 :license: Apache License, Version 2.0, see LICENSE for details.
8 """
9 import re
10 
11 
12 def pyfloat(v_str):
13  """Convert string repr of Fortran floating point to Python double."""
14  # NOTE: There is no loss of information from SP to DP floats
15 
16  return float(re.sub('(?<=[^eEdD])(?=[+-])', 'e',
17  v_str.lower().replace('d', 'e')))
18 
19 
20 def pycomplex(v_str):
21  """Convert string repr of Fortran complex to Python complex."""
22  assert isinstance(v_str, str)
23 
24  if v_str[0] == '(' and v_str[-1] == ')' and len(v_str.split(',')) == 2:
25  v_re, v_im = v_str[1:-1].split(',', 1)
26 
27  # NOTE: Failed float(str) will raise ValueError
28  return complex(pyfloat(v_re), pyfloat(v_im))
29  else:
30  raise ValueError('{0} must be in complex number form (x, y).'
31  ''.format(v_str))
32 
33 
34 def pybool(v_str, strict_logical=True):
35  """Convert string repr of Fortran logical to Python logical."""
36  assert isinstance(v_str, str)
37  assert isinstance(strict_logical, bool)
38 
39  if strict_logical:
40  v_bool = v_str.lower()
41  else:
42  try:
43  if v_str.startswith('.'):
44  v_bool = v_str[1].lower()
45  else:
46  v_bool = v_str[0].lower()
47  except IndexError:
48  raise ValueError('{0} is not a valid logical constant.'
49  ''.format(v_str))
50 
51  if v_bool in ('.true.', '.t.', 'true', 't'):
52  return True
53  elif v_bool in ('.false.', '.f.', 'false', 'f'):
54  return False
55  else:
56  raise ValueError('{0} is not a valid logical constant.'.format(v_str))
57 
58 
59 def pystr(v_str):
60  """Convert string repr of Fortran string to Python string."""
61  assert isinstance(v_str, str)
62 
63  if v_str[0] in ("'", '"') and v_str[0] == v_str[-1]:
64  quote = v_str[0]
65  out = v_str[1:-1]
66  else:
67  # NOTE: This is non-standard Fortran.
68  # For example, gfortran rejects non-delimited strings.
69  quote = None
70  out = v_str
71 
72  # Replace escaped strings
73  if quote:
74  out = out.replace(2 * quote, quote)
75 
76  return out
def pystr(v_str)
Definition: fpy.py:59
def pybool(v_str, strict_logical=True)
Definition: fpy.py:34
def pyfloat(v_str)
Definition: fpy.py:12
def pycomplex(v_str)
Definition: fpy.py:20