Skip to content

Commit 9d1a733

Browse files
lukelbdTry2Code
authored andcommitted
Pep8 compliant whitespace and remove unneeded ()
1 parent 89493cf commit 9d1a733

File tree

1 file changed

+47
-49
lines changed

1 file changed

+47
-49
lines changed

python/cdo.py

Lines changed: 47 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -152,26 +152,25 @@ def __init__(self,
152152
self._cmd = cmd
153153
self._options = options
154154

155-
self.operators = self.__getOperators()
156-
self.noOutputOperators = [
157-
op for op in self.operators.keys() if 0 == self.operators[op]]
155+
self.operators = self.__getOperators()
156+
self.noOutputOperators = [op for op, num in self.operators.items() if 0 == num]
158157
self.returnNoneOnError = returnNoneOnError
159-
self.tempStore = tempStore or CdoTempfileStore(dir=tempdir)
160-
self.forceOutput = forceOutput
161-
self.env = env
162-
self.debug = True if 'DEBUG' in os.environ else debug
163-
self.libs = self.getSupportedLibs()
158+
self.tempStore = tempStore or CdoTempfileStore(dir=tempdir)
159+
self.forceOutput = forceOutput
160+
self.env = env
161+
self.debug = True if 'DEBUG' in os.environ else debug
162+
self.libs = self.getSupportedLibs()
164163

165164
# optional IO libraries for additional return types {{{
166-
self.hasNetcdf = False
167-
self.hasXarray = False
168-
self.cdf = None
169-
self.xa_open = None
165+
self.hasNetcdf = False
166+
self.hasXarray = False
167+
self.cdf = None
168+
self.xa_open = None
170169
self.__loadOptionalLibs()
171170

172171
self.logging = logging # internal logging {{{
173172
self.logFile = logFile
174-
if (self.logging):
173+
if self.logging:
175174
self.logger = setupLogging(self.logFile) # }}}
176175

177176
def __get__(self, instance, owner):
@@ -183,8 +182,8 @@ def __get__(self, instance, owner):
183182
# renamed to 'seq' in 1.9.7.
184183
# This workaround translates all calls of 'seq' into for in case of
185184
# versions prior to 1.9.7
186-
if name in self.AliasOperators.keys() and \
187-
(parse_version(getCdoVersion(self.CDO)) < parse_version('1.9.7')):
185+
if name in self.AliasOperators and (
186+
parse_version(getCdoVersion(self.CDO)) < parse_version('1.9.7')):
188187
name = self.AliasOperators[name]
189188
return self.__class__(
190189
instance.CDO,
@@ -201,9 +200,9 @@ def __get__(self, instance, owner):
201200

202201
# from 1.9.6 onwards CDO returns 1 of diff* finds a difference
203202
def __exit_success(self, operatorName):
204-
if (parse_version(getCdoVersion(self.CDO)) < parse_version('1.9.6')):
203+
if parse_version(getCdoVersion(self.CDO)) < parse_version('1.9.6'):
205204
return 0
206-
if ('diff' != operatorName[0:4]):
205+
if 'diff' != operatorName[0:4]:
207206
return 0
208207
return 1
209208

@@ -213,15 +212,15 @@ def __getOperators(self): # {{{
213212
operators = {}
214213

215214
version = parse_version(getCdoVersion(self.CDO))
216-
if (version < parse_version('1.7.2')):
215+
if version < parse_version('1.7.2'):
217216
proc = subprocess.Popen(
218217
[self.CDO, '-h'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
219-
ret = proc.communicate()
220-
l = ret[1].decode("utf-8").find("Operators:")
221-
ops = ret[1].decode("utf-8")[l:-1].split(os.linesep)[1:-1]
218+
ret = proc.communicate()
219+
l = ret[1].decode("utf-8").find("Operators:")
220+
ops = ret[1].decode("utf-8")[l:-1].split(os.linesep)[1:-1]
222221
endI = ops.index('')
223-
s = ' '.join(ops[:endI]).strip()
224-
s = re.sub(r"\s+", " ", s)
222+
s = ' '.join(ops[:endI]).strip()
223+
s = re.sub(r"\s+", " ", s)
225224

226225
for op in list(set(s.split(" "))):
227226
operators[op] = 1
@@ -232,7 +231,7 @@ def __getOperators(self): # {{{
232231
if op in self.MoreOutputOperators:
233232
operators[op] = -1
234233

235-
elif (version < parse_version('1.8.0') or parse_version('1.9.0') == version):
234+
elif version < parse_version('1.8.0') or parse_version('1.9.0') == version:
236235
proc = subprocess.Popen([self.CDO, '--operators'],
237236
stderr=subprocess.PIPE, stdout=subprocess.PIPE)
238237
ret = proc.communicate()
@@ -248,7 +247,7 @@ def __getOperators(self): # {{{
248247
if op in self.MoreOutputOperators:
249248
operators[op] = -1
250249

251-
elif (version < parse_version('1.9.3')):
250+
elif version < parse_version('1.9.3'):
252251
proc = subprocess.Popen([self.CDO, '--operators'],
253252
stderr=subprocess.PIPE, stdout=subprocess.PIPE)
254253
ret = proc.communicate()
@@ -278,8 +277,8 @@ def __getOperators(self): # {{{
278277
ret = proc.communicate()
279278
ops = list(map(lambda x: x.split(' ')[0], ret[0].decode(
280279
"utf-8")[0:-1].split(os.linesep)))
281-
ios = list(map(lambda x: x.split(' ')
282-
[-1], ret[0].decode("utf-8")[0:-1].split(os.linesep)))
280+
ios = list(map(lambda x: x.split(' ')[-1], ret[0].decode(
281+
"utf-8")[0:-1].split(os.linesep)))
283282

284283
for i, op in enumerate(ops):
285284
operators[op] = int(ios[i][1:len(ios[i]) - 1].split('|')[1])
@@ -311,10 +310,10 @@ def __call(self, cmd, envOfCall={}):
311310
# print("ENV: " + k + " = " + v)
312311
print('CALL :' + ' '.join(cmd))
313312
print('STDOUT:')
314-
if (0 != len(stdout.strip())):
313+
if 0 != len(stdout.strip()):
315314
print(stdout)
316315
print('STDERR:')
317-
if (0 != len(stderr.strip())):
316+
if 0 != len(stderr.strip()):
318317
print(stderr)
319318
# }}}
320319
print('# DEBUG - end ===============================================================')
@@ -323,9 +322,9 @@ def __call(self, cmd, envOfCall={}):
323322

324323
# error handling for CDO calls
325324
def __hasError(self, method_name, cmd, retvals): # {{{
326-
if (self.debug):
325+
if self.debug:
327326
print("RETURNCODE:" + retvals["returncode"].__str__())
328-
if (self.__exit_success(method_name) < retvals["returncode"]):
327+
if self.__exit_success(method_name) < retvals["returncode"]:
329328
print("Error in calling operator " + method_name + " with:")
330329
print(">>> " + ' '.join(cmd) + "<<<")
331330
print('STDOUT:' + retvals["stdout"])
@@ -349,10 +348,10 @@ def __loadOptionalLibs(self):
349348

350349
try:
351350
from netCDF4 import Dataset as cdf
352-
self.cdf = cdf
353-
self.hasNetcdf = True
354351
import numpy as np
355-
self.np = np
352+
self.hasNetcdf = True
353+
self.cdf = cdf
354+
self.np = np
356355
except Exception:
357356
print("-->> Could not load netCDF4! <<--") # }}}
358357

@@ -362,7 +361,7 @@ def infile(self, *infiles):
362361
self._cmd.append(infile)
363362
elif self.hasXarray:
364363
import xarray # <<-- python2 workaround
365-
if (type(infile) == xarray.core.dataset.Dataset):
364+
if type(infile) == xarray.core.dataset.Dataset:
366365
# create a temp nc file from input data
367366
tmpfile = self.tempStore.newFile()
368367
infile.to_netcdf(tmpfile)
@@ -417,7 +416,7 @@ def __call__(self, *args, **kwargs):
417416
cmd.append(' '.join(kwargs["input"]))
418417
elif self.hasXarray:
419418
import xarray # <<-- python2 workaround
420-
if (type(kwargs["input"]) == xarray.core.dataset.Dataset):
419+
if type(kwargs["input"]) == xarray.core.dataset.Dataset:
421420
# create a temp nc file from input data
422421
tmpfile = self.tempStore.newFile()
423422
kwargs["input"].to_netcdf(tmpfile)
@@ -452,12 +451,12 @@ def __call__(self, *args, **kwargs):
452451

453452
if operatorPrintsOut:
454453
retvals = self.__call(cmd, envOfCall)
455-
if (not self.__hasError(method_name, cmd, retvals)):
454+
if not self.__hasError(method_name, cmd, retvals):
456455
r = list(map(strip, retvals["stdout"].split(os.linesep)))
457456
if "autoSplit" in kwargs:
458457
splitString = kwargs["autoSplit"]
459458
_output = [x.split(splitString) for x in r[:len(r) - 1]]
460-
if (1 == len(_output)):
459+
if 1 == len(_output):
461460
return _output[0]
462461
else:
463462
return _output
@@ -514,22 +513,21 @@ def __call__(self, *args, **kwargs):
514513
return [self.readXDataset(file) for file in outputs]
515514

516515
# handle split-operator outputs
517-
elif ('split' == method_name[0:5]):
516+
elif 'split' == method_name[0:5]:
518517
return glob.glob(kwargs["output"] + '*')
519518

520519
# default: return filename (given or tempfile)
521520
else:
522-
if (1 == len(outputs)):
521+
if 1 == len(outputs):
523522
return outputs[0]
524523
else:
525524
return outputs
526525

527526
def __getattr__(self, method_name): # main method-call handling for Cdo-objects {{{
528-
if (method_name in self.__dict__) \
529-
or (method_name in list(self.operators.keys())) \
530-
or (method_name in self.AliasOperators):
527+
if any(method_name in opts for opts in (
528+
self.__dict__, self.operators, self.AliasOperators)):
531529
if self.debug:
532-
print(("Found method:" + method_name))
530+
print(("Found operator:" + method_name))
533531

534532
# cache the method for later
535533
class Operator(self.__class__):
@@ -548,14 +546,14 @@ def __init__(self, *args, **kwargs):
548546
else:
549547
# given method might match part of know operators: autocompletion
550548
func = lambda x: re.search(method_name, x)
551-
options = list(filter(func, self.operators.keys()))
549+
options = list(filter(func, self.operators))
552550
message = "Unknown operator '" + method_name + "'!"
553551
if 0 != len(options):
554552
message += " Did you mean: " + ", ".join(options) + "?"
555553
raise AttributeError(message)
556554
# }}}
557555

558-
def getSupportedLibs(self, force=False):
556+
def getSupportedLibs(self):
559557
proc = subprocess.Popen(self.CDO + ' -V',
560558
shell=True,
561559
stdout=subprocess.PIPE,
@@ -628,7 +626,7 @@ def getCdo(self):
628626
return self.CDO
629627

630628
def hasLib(self, lib):
631-
return (lib in self.libs.keys())
629+
return lib in self.libs
632630

633631
def libsVersion(self, lib):
634632
if not self.hasLib(lib):
@@ -645,8 +643,8 @@ def cleanTempDir(self):
645643

646644
# make use of internal documentation structure of python
647645
def __dir__(self):
648-
res = dir(type(self)) + list(self.__dict__.keys())
649-
res.extend(list(self.operators.keys()))
646+
res = dir(type(self)) + list(self.__dict__)
647+
res.extend(list(self.operators))
650648
return res
651649

652650
# ==================================================================

0 commit comments

Comments
 (0)