Skip to content

Commit 4a7456a

Browse files
committed
fix(SU2_PY): Python 3 correctness and PEP 8 fixes
- Use identity operators for None comparisons (is/is not) - Replace bare except with Exception/OSError - Replace .has_key() and .iteritems() with Python 3 equivalents - Fix mutable default arguments in function signatures Signed-off-by: shbhmexe <[email protected]>
1 parent e1befed commit 4a7456a

File tree

11 files changed

+42
-40
lines changed

11 files changed

+42
-40
lines changed

SU2_PY/SU2/io/data.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def load_data(file_name, var_names=None, file_format="infer", core_name="python_
115115
#: with filelock
116116

117117
# load specified varname into dictionary
118-
if var_names != None:
118+
if var_names is not None:
119119
# check for one item name array
120120
if isinstance(var_names, str):
121121
var_names = [
@@ -196,7 +196,7 @@ def save_data(
196196
core_name=core_name,
197197
)
198198
# check for keys not in new data
199-
for key, value in data_dict_old.iteritems():
199+
for key, value in data_dict_old.items():
200200
if not (key in data_dict):
201201
data_dict[key] = value
202202
#: for each dict item
@@ -365,7 +365,7 @@ def rec2dict(array_in):
365365
# convert array
366366
elif isinstance(value, numpy.ndarray):
367367
# check for another struct level
368-
if value.dtype.names == None:
368+
if value.dtype.names is None:
369369
value = value.tolist()
370370
# telescoping
371371
else:
@@ -418,7 +418,7 @@ def append_nestdict(base_dict, add_dict):
418418
for key in add_dict.keys():
419419

420420
# ensure base_dict key exists and is a list
421-
if not base_dict.has_key(key):
421+
if key not in base_dict:
422422
if isinstance(add_dict[key], dict):
423423
base_dict[key] = {}
424424
else:

SU2_PY/SU2/io/state.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def State_Factory(state=None, config=None):
111111
config = state
112112
state = None
113113

114-
if not state is None:
114+
if state is not None:
115115
assert isinstance(state, State), "input is must be a state instance"
116116
return state
117117

SU2_PY/SU2/io/tools.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -45,18 +45,17 @@ def read_gradients(Grad_filename, scale=1.0):
4545
"""
4646

4747
# open file and skip first line
48-
gradfile = open(Grad_filename)
49-
gradfile.readline()
50-
51-
# read values
52-
grad_vals = []
53-
for line in gradfile:
54-
line = line.strip()
55-
if len(line) == 0:
56-
break
57-
grad_vals.append(float(line) * scale)
58-
#: for each line
59-
48+
with open(Grad_filename) as gradfile:
49+
gradfile.readline()
50+
51+
# read values
52+
grad_vals = []
53+
for line in gradfile:
54+
line = line.strip()
55+
if len(line) == 0:
56+
break
57+
grad_vals.append(float(line) * scale)
58+
# done
6059
return grad_vals
6160

6261

@@ -387,7 +386,7 @@ def read_aerodynamics(
387386
Func_Values[key] = history_data["TAVG_" + key][-1]
388387
else:
389388
# in steady cases take only last value.
390-
for key, value in Func_Values.iteritems():
389+
for key, value in Func_Values.items():
391390
if not history_data.get(key):
392391
raise KeyError(
393392
"Key "
@@ -641,7 +640,7 @@ def get_dvID(kindName):
641640
try:
642641
return id_map[kindName]
643642
except KeyError:
644-
raise Exception("Unrecognized Design Variable Name: %s", kindName)
643+
raise Exception("Unrecognized Design Variable Name: %s" % kindName)
645644

646645

647646
#: def get_dvID()
@@ -652,7 +651,10 @@ def get_dvID(kindName):
652651
# -------------------------------------------------------------------
653652

654653

655-
def get_gradFileFormat(grad_type, plot_format, kindID, special_cases=[]):
654+
def get_gradFileFormat(grad_type, plot_format, kindID, special_cases=None):
655+
656+
if special_cases is None:
657+
special_cases = []
656658

657659
# start header, build a list of strings and join at the end
658660
header = []
@@ -731,7 +733,7 @@ def get_gradFileFormat(grad_type, plot_format, kindID, special_cases=[]):
731733
write_format.append(r", %s, %s, %s")
732734
elif kindID == "CST":
733735
header.append(r',"Up/Down","Kulfan number", "Total Kulfan numbers"')
734-
write_format.append(r", %s, %s", "%s")
736+
write_format.append(r", %s, %s, %s")
735737
elif kindID == "FAIRING":
736738
header.append(r',"ControlPoint_Index","Theta_Disp","R_Disp"')
737739
write_format.append(r", %s, %s, %s")
@@ -1170,7 +1172,7 @@ def make_link(src, dst):
11701172
os.symlink(src, dst)
11711173

11721174

1173-
def restart2solution(config, state={}):
1175+
def restart2solution(config, state=None):
11741176
"""restart2solution(config,state={})
11751177
moves restart file to solution file,
11761178
optionally updates state

SU2_PY/SU2/run/interface.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,9 @@
5656
mpi_Command = os.environ["SU2_MPI_COMMAND"]
5757
elif slurm_job:
5858
mpi_Command = "srun -n %i %s"
59-
elif not which("mpirun") is None:
59+
elif which("mpirun") is not None:
6060
mpi_Command = "mpirun -n %i %s"
61-
elif not which("mpiexec") is None:
61+
elif which("mpiexec") is not None:
6262
mpi_Command = "mpiexec -n %i %s"
6363
else:
6464
mpi_Command = ""

SU2_PY/SU2/run/projection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
# ----------------------------------------------------------------------
4242

4343

44-
def projection(config, state={}, step=1e-3):
44+
def projection(config, state=None, step=1e-3):
4545
"""info = SU2.run.projection(config,state,step=1e-3)
4646
4747
Runs an gradient projection with:

SU2_PY/SU2/util/plot.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,9 @@ def write_plot(filename, plot_format, data_plot, keys_plot=None):
8888
return
8989

9090

91-
def tecplot(filename, data_plot, keys_plot=[]):
91+
def tecplot(filename, data_plot, keys_plot=None):
9292
write_plot(filename, "TECPLOT", data_plot, keys_plot)
9393

9494

95-
def paraview(filename, data_plot, keys_plot=[]):
95+
def paraview(filename, data_plot, keys_plot=None):
9696
write_plot(filename, "CSV", data_plot, keys_plot)

SU2_PY/SU2_CFD.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ def main():
120120
options.wave_equation = options.wave_equation.upper() == "TRUE"
121121
options.heat_equation = options.heat_equation.upper() == "TRUE"
122122

123-
if options.filename == None:
123+
if options.filename is None:
124124
raise Exception("No config file provided. Use -f flag")
125125

126126
if options.with_MPI == True:
@@ -163,7 +163,7 @@ def main():
163163
# Finalize the solver and exit cleanly
164164
SU2Driver.Finalize()
165165

166-
if SU2Driver != None:
166+
if SU2Driver is not None:
167167
del SU2Driver
168168

169169

SU2_PY/parallel_computation.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def main():
6464
options.partitions = int(options.partitions)
6565
options.compute = options.compute.upper() == "TRUE"
6666

67-
if options.filename == None:
67+
if options.filename is None:
6868
raise Exception("No config file provided. Use -f flag")
6969

7070
parallel_computation(options.filename, options.partitions, options.compute)

SU2_PY/parallel_computation_fsi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def main():
6464
options.partitions = int(options.partitions)
6565
options.compute = options.compute.upper() == "TRUE"
6666

67-
if options.filename == None:
67+
if options.filename is None:
6868
raise Exception("No config file provided. Use -f flag")
6969

7070
parallel_computation(options.filename, options.partitions, options.compute)

SU2_PY/topology_optimization.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def obj_val(self, x):
123123
# clear previous output and run direct solver
124124
try:
125125
os.remove(self._objValFile)
126-
except:
126+
except OSError:
127127
pass
128128

129129
try:
@@ -136,7 +136,7 @@ def obj_val(self, x):
136136
break
137137
# the return code of mpirun is useless, we test the value of the function
138138
self._assert_isfinite(val)
139-
except:
139+
except Exception:
140140
raise RuntimeError("Objective function evaluation failed")
141141
# end
142142

@@ -150,7 +150,7 @@ def obj_der(self, x):
150150
# clear previous output and run direct solver
151151
try:
152152
os.remove(self._objDerFile)
153-
except:
153+
except OSError:
154154
pass
155155
N = x.shape[0]
156156
y = np.ndarray((N,))
@@ -167,7 +167,7 @@ def obj_der(self, x):
167167
self._assert_isfinite(val)
168168
y[i] = val * obj_scale / var_scale
169169
# end
170-
except:
170+
except Exception:
171171
raise RuntimeError("Objective gradient evaluation failed")
172172
# end
173173

@@ -186,7 +186,7 @@ def con_val(self, x):
186186
val = float(lines[1].split(",")[col])
187187
break
188188
self._assert_isfinite(val)
189-
except:
189+
except Exception:
190190
raise RuntimeError("Constraint function evaluation failed")
191191
# end
192192

@@ -200,7 +200,7 @@ def con_der(self, x):
200200
# clear previous output and run solver
201201
try:
202202
os.remove(self._conDerFile)
203-
except:
203+
except OSError:
204204
pass
205205
N = x.shape[0]
206206
y = np.ndarray((N,))
@@ -217,7 +217,7 @@ def con_der(self, x):
217217
self._assert_isfinite(val)
218218
y[i] = val * con_scale / var_scale
219219
# end
220-
except:
220+
except Exception:
221221
raise RuntimeError("Constraint function evaluation failed")
222222
# end
223223

@@ -295,7 +295,7 @@ def finished(self):
295295
return self._value == self._maxi
296296

297297
def value(self):
298-
if self._func == None:
298+
if self._func is None:
299299
return self._value
300300
else:
301301
return self._func(self._value)

0 commit comments

Comments
 (0)