Skip to content

Commit c4faf7e

Browse files
cchung100mUbuntu
authored andcommitted
[MXNET-1411] solve pylint error issue#14851 (apache#15113)
* fix pylint error: no-else-raise in _export_helper.py * fix pylint error: no-else-raise in _translation_utils.py * fix pylint error: Bad option value 'no-else-raise' (bad-option-value) in vocab.py * fix pylint error: Bad option value 'no-else-raise' (bad-option-value) in trainer.py * fix pylint error: Bad option value 'no-else-raise' (bad-option-value) in utils.py * fix pylint error: Bad option value 'no-else-raise' (bad-option-value) in detection.py * fix pylint error: Bad option value 'no-else-raise' (bad-option-value) in image.py * fix pylint error: Bad option value 'no-else-raise' (bad-option-value) in model.py * fix pylint error: Bad option value 'no-else-raise' (bad-option-value) in sparse.py * fix pylint error: Bad option value 'no-else-raise' (bad-option-value) in test_utils.py * fix pylint error: R1720: Unnecessary else after raise (no-else-raise) for vocab.py * fix pylint error: R1720: Unnecessary else after raise (no-else-raise) for model.py * fix pylint error: R1720: Unnecessary else after raise (no-else-raise) for _translation_utils.py * fix pylint error: R1720: Unnecessary else after raise (no-else-raise) for _export_helper.py * fix pylint error: R1720: Unnecessary else after raise (no-else-raise) for test_utils.py * fix pylint error: R1720: Unnecessary else after raise (no-else-raise) for image.py * fix pylint error: R1720: Unnecessary else after raise (no-else-raise) for trainer.py * fix pylint error: R1720: Unnecessary else after raise (no-else-raise) for detection.py * fix pylint error: R1720: Unnecessary else after raise (no-else-raise) for utils.py * fix pylint error: R1720: Unnecessary else after raise (no-else-raise) for sparse.py * fix pylint error:R1719: The if expression can be replaced with 'bool(test)' (simplifiable-if-expression)
1 parent e0919b0 commit c4faf7e

File tree

10 files changed

+88
-90
lines changed

10 files changed

+88
-90
lines changed

python/mxnet/contrib/onnx/mx2onnx/_export_helper.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -40,26 +40,26 @@ def load_module(sym_filepath, params_filepath):
4040
params : params object
4141
Model weights including both arg and aux params.
4242
"""
43-
if not (os.path.isfile(sym_filepath) and os.path.isfile(params_filepath)): # pylint: disable=no-else-raise
43+
if not (os.path.isfile(sym_filepath) and os.path.isfile(params_filepath)):
4444
raise ValueError("Symbol and params files provided are invalid")
45-
else:
46-
try:
47-
# reads symbol.json file from given path and
48-
# retrieves model prefix and number of epochs
49-
model_name = sym_filepath.rsplit('.', 1)[0].rsplit('-', 1)[0]
50-
params_file_list = params_filepath.rsplit('.', 1)[0].rsplit('-', 1)
51-
# Setting num_epochs to 0 if not present in filename
52-
num_epochs = 0 if len(params_file_list) == 1 else int(params_file_list[1])
53-
except IndexError:
54-
logging.info("Model and params name should be in format: "
55-
"prefix-symbol.json, prefix-epoch.params")
56-
raise
5745

58-
sym, arg_params, aux_params = mx.model.load_checkpoint(model_name, num_epochs)
46+
try:
47+
# reads symbol.json file from given path and
48+
# retrieves model prefix and number of epochs
49+
model_name = sym_filepath.rsplit('.', 1)[0].rsplit('-', 1)[0]
50+
params_file_list = params_filepath.rsplit('.', 1)[0].rsplit('-', 1)
51+
# Setting num_epochs to 0 if not present in filename
52+
num_epochs = 0 if len(params_file_list) == 1 else int(params_file_list[1])
53+
except IndexError:
54+
logging.info("Model and params name should be in format: "
55+
"prefix-symbol.json, prefix-epoch.params")
56+
raise
5957

60-
# Merging arg and aux parameters
61-
params = {}
62-
params.update(arg_params)
63-
params.update(aux_params)
58+
sym, arg_params, aux_params = mx.model.load_checkpoint(model_name, num_epochs)
6459

65-
return sym, params
60+
# Merging arg and aux parameters
61+
params = {}
62+
params.update(arg_params)
63+
params.update(aux_params)
64+
65+
return sym, params

python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -178,23 +178,23 @@ def _fix_channels(op_name, attrs, inputs, proto_obj):
178178
these attributes. We check the shape of weights provided to get the number.
179179
"""
180180
weight_name = inputs[1].name
181-
if not weight_name in proto_obj._params: # pylint: disable=no-else-raise
181+
if not weight_name in proto_obj._params:
182182
raise ValueError("Unable to get channels/units attr from onnx graph.")
183-
else:
184-
wshape = proto_obj._params[weight_name].shape
185-
assert len(wshape) >= 2, "Weights shape is invalid: {}".format(wshape)
186183

187-
if op_name == 'FullyConnected':
188-
attrs['num_hidden'] = wshape[0]
189-
else:
190-
if op_name == 'Convolution':
191-
# Weight shape for Conv and FC: (M x C x kH x kW) : M is number of
192-
# feature maps/hidden and C is number of channels
193-
attrs['num_filter'] = wshape[0]
194-
elif op_name == 'Deconvolution':
195-
# Weight shape for DeConv : (C x M x kH x kW) : M is number of
196-
# feature maps/filters and C is number of channels
197-
attrs['num_filter'] = wshape[1]
184+
wshape = proto_obj._params[weight_name].shape
185+
assert len(wshape) >= 2, "Weights shape is invalid: {}".format(wshape)
186+
187+
if op_name == 'FullyConnected':
188+
attrs['num_hidden'] = wshape[0]
189+
else:
190+
if op_name == 'Convolution':
191+
# Weight shape for Conv and FC: (M x C x kH x kW) : M is number of
192+
# feature maps/hidden and C is number of channels
193+
attrs['num_filter'] = wshape[0]
194+
elif op_name == 'Deconvolution':
195+
# Weight shape for DeConv : (C x M x kH x kW) : M is number of
196+
# feature maps/filters and C is number of channels
197+
attrs['num_filter'] = wshape[1]
198198
return attrs
199199

200200

python/mxnet/contrib/text/vocab.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -210,9 +210,8 @@ def to_tokens(self, indices):
210210

211211
tokens = []
212212
for idx in indices:
213-
if not isinstance(idx, int) or idx > max_idx: # pylint: disable=no-else-raise
213+
if not isinstance(idx, int) or idx > max_idx:
214214
raise ValueError('Token index %d in the provided `indices` is invalid.' % idx)
215-
else:
216-
tokens.append(self.idx_to_token[idx])
215+
tokens.append(self.idx_to_token[idx])
217216

218217
return tokens[0] if to_reduce else tokens

python/mxnet/gluon/trainer.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -249,11 +249,11 @@ def _init_kvstore(self):
249249

250250
@property
251251
def learning_rate(self):
252-
if not isinstance(self._optimizer, opt.Optimizer): # pylint: disable=no-else-raise
252+
if not isinstance(self._optimizer, opt.Optimizer):
253253
raise UserWarning("Optimizer has to be defined before its learning "
254254
"rate can be accessed.")
255-
else:
256-
return self._optimizer.learning_rate
255+
256+
return self._optimizer.learning_rate
257257

258258
@property
259259
def optimizer(self):
@@ -270,11 +270,11 @@ def set_learning_rate(self, lr):
270270
lr : float
271271
The new learning rate of the optimizer.
272272
"""
273-
if not isinstance(self._optimizer, opt.Optimizer): # pylint: disable=no-else-raise
273+
if not isinstance(self._optimizer, opt.Optimizer):
274274
raise UserWarning("Optimizer has to be defined before its learning "
275275
"rate is mutated.")
276-
else:
277-
self._optimizer.set_learning_rate(lr)
276+
277+
self._optimizer.set_learning_rate(lr)
278278

279279
def _row_sparse_pull(self, parameter, out, row_id, full_idx=False):
280280
"""Internal method to invoke pull operations on KVStore. If `full_idx` is set to True,

python/mxnet/gluon/utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -341,11 +341,11 @@ def download(url, path=None, overwrite=False, sha1_hash=None, retries=5, verify_
341341
break
342342
except Exception as e:
343343
retries -= 1
344-
if retries <= 0: # pylint: disable=no-else-raise
344+
if retries <= 0:
345345
raise e
346-
else:
347-
print('download failed due to {}, retrying, {} attempt{} left'
348-
.format(repr(e), retries, 's' if retries > 1 else ''))
346+
347+
print('download failed due to {}, retrying, {} attempt{} left'
348+
.format(repr(e), retries, 's' if retries > 1 else ''))
349349

350350
return fname
351351

python/mxnet/image/detection.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -809,23 +809,23 @@ def next(self):
809809
pad = batch_size - i
810810
# handle padding for the last batch
811811
if pad != 0:
812-
if self.last_batch_handle == 'discard': # pylint: disable=no-else-raise
812+
if self.last_batch_handle == 'discard':
813813
raise StopIteration
814814
# if the option is 'roll_over', throw StopIteration and cache the data
815-
elif self.last_batch_handle == 'roll_over' and \
815+
if self.last_batch_handle == 'roll_over' and \
816816
self._cache_data is None:
817817
self._cache_data = batch_data
818818
self._cache_label = batch_label
819819
self._cache_idx = i
820820
raise StopIteration
821+
822+
_ = self._batchify(batch_data, batch_label, i)
823+
if self.last_batch_handle == 'pad':
824+
self._allow_read = False
821825
else:
822-
_ = self._batchify(batch_data, batch_label, i)
823-
if self.last_batch_handle == 'pad':
824-
self._allow_read = False
825-
else:
826-
self._cache_data = None
827-
self._cache_label = None
828-
self._cache_idx = None
826+
self._cache_data = None
827+
self._cache_label = None
828+
self._cache_idx = None
829829

830830
return io.DataBatch([batch_data], [batch_label], pad=pad)
831831

python/mxnet/image/image.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1198,10 +1198,10 @@ def __init__(self, batch_size, data_shape, label_width=1,
11981198
logging.info('%s: loading recordio %s...',
11991199
class_name, path_imgrec)
12001200
if path_imgidx:
1201-
self.imgrec = recordio.MXIndexedRecordIO(path_imgidx, path_imgrec, 'r') # pylint: disable=redefined-variable-type
1201+
self.imgrec = recordio.MXIndexedRecordIO(path_imgidx, path_imgrec, 'r')
12021202
self.imgidx = list(self.imgrec.keys)
12031203
else:
1204-
self.imgrec = recordio.MXRecordIO(path_imgrec, 'r') # pylint: disable=redefined-variable-type
1204+
self.imgrec = recordio.MXRecordIO(path_imgrec, 'r')
12051205
self.imgidx = None
12061206
else:
12071207
self.imgrec = None
@@ -1224,7 +1224,7 @@ def __init__(self, batch_size, data_shape, label_width=1,
12241224
imgkeys = []
12251225
index = 1
12261226
for img in imglist:
1227-
key = str(index) # pylint: disable=redefined-variable-type
1227+
key = str(index)
12281228
index += 1
12291229
if len(img) > 2:
12301230
label = nd.array(img[:-1], dtype=dtype)
@@ -1374,23 +1374,23 @@ def next(self):
13741374
pad = batch_size - i
13751375
# handle padding for the last batch
13761376
if pad != 0:
1377-
if self.last_batch_handle == 'discard': # pylint: disable=no-else-raise
1377+
if self.last_batch_handle == 'discard':
13781378
raise StopIteration
13791379
# if the option is 'roll_over', throw StopIteration and cache the data
1380-
elif self.last_batch_handle == 'roll_over' and \
1380+
if self.last_batch_handle == 'roll_over' and \
13811381
self._cache_data is None:
13821382
self._cache_data = batch_data
13831383
self._cache_label = batch_label
13841384
self._cache_idx = i
13851385
raise StopIteration
1386+
1387+
_ = self._batchify(batch_data, batch_label, i)
1388+
if self.last_batch_handle == 'pad':
1389+
self._allow_read = False
13861390
else:
1387-
_ = self._batchify(batch_data, batch_label, i)
1388-
if self.last_batch_handle == 'pad':
1389-
self._allow_read = False
1390-
else:
1391-
self._cache_data = None
1392-
self._cache_label = None
1393-
self._cache_idx = None
1391+
self._cache_data = None
1392+
self._cache_label = None
1393+
self._cache_idx = None
13941394

13951395
return io.DataBatch([batch_data], [batch_label], pad=pad)
13961396

python/mxnet/model.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -642,10 +642,9 @@ def _init_iter(self, X, y, is_train):
642642
"""Initialize the iterator given input."""
643643
if isinstance(X, (np.ndarray, nd.NDArray)):
644644
if y is None:
645-
if is_train: # pylint: disable=no-else-raise
645+
if is_train:
646646
raise ValueError('y must be specified when X is numpy.ndarray')
647-
else:
648-
y = np.zeros(X.shape[0])
647+
y = np.zeros(X.shape[0])
649648
if not isinstance(y, (np.ndarray, nd.NDArray)):
650649
raise TypeError('y must be ndarray when X is numpy.ndarray')
651650
if X.shape[0] != y.shape[0]:

python/mxnet/ndarray/sparse.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -639,10 +639,10 @@ def __getitem__(self, key):
639639
if isinstance(key, int):
640640
raise Exception("__getitem__ with int key is not implemented for RowSparseNDArray yet")
641641
if isinstance(key, py_slice):
642-
if key.step is not None or key.start is not None or key.stop is not None: # pylint: disable=no-else-raise
642+
if key.step is not None or key.start is not None or key.stop is not None:
643643
raise Exception('RowSparseNDArray only supports [:] for __getitem__')
644-
else:
645-
return self
644+
645+
return self
646646
if isinstance(key, tuple):
647647
raise ValueError('Multi-dimension indexing is not supported')
648648
raise ValueError('Undefined behaviour for {}'.format(key))
@@ -1102,9 +1102,9 @@ def row_sparse_array(arg1, shape=None, ctx=None, dtype=None):
11021102
# construct a row sparse array from (D0, D1 ..) or (data, indices)
11031103
if isinstance(arg1, tuple):
11041104
arg_len = len(arg1)
1105-
if arg_len < 2: # pylint: disable=no-else-raise
1105+
if arg_len < 2:
11061106
raise ValueError("Unexpected length of input tuple: " + str(arg_len))
1107-
elif arg_len > 2:
1107+
if arg_len > 2:
11081108
# empty ndarray with shape
11091109
_check_shape(arg1, shape)
11101110
return empty('row_sparse', arg1, ctx=ctx, dtype=dtype)

python/mxnet/test_utils.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -212,11 +212,11 @@ def _get_powerlaw_dataset_csr(num_rows, num_cols, density=0.1, dtype=None):
212212
return mx.nd.array(output_arr).tostype("csr")
213213
col_max = col_max * 2
214214

215-
if unused_nnz > 0: # pylint: disable=no-else-raise
215+
if unused_nnz > 0:
216216
raise ValueError("not supported for this density: %s"
217217
" for this shape (%s,%s)" % (density, num_rows, num_cols))
218-
else:
219-
return mx.nd.array(output_arr).tostype("csr")
218+
219+
return mx.nd.array(output_arr).tostype("csr")
220220

221221

222222
def assign_each(the_input, function):
@@ -1407,10 +1407,10 @@ def check_consistency(sym, ctx_list, scale=1.0, grad_req='write',
14071407
except AssertionError as e:
14081408
print('Predict Err: ctx %d vs ctx %d at %s'%(i, max_idx, name))
14091409
traceback.print_exc()
1410-
if raise_on_err: # pylint: disable=no-else-raise
1410+
if raise_on_err:
14111411
raise e
1412-
else:
1413-
print(str(e))
1412+
1413+
print(str(e))
14141414

14151415
# train
14161416
if grad_req != 'null':
@@ -1434,10 +1434,10 @@ def check_consistency(sym, ctx_list, scale=1.0, grad_req='write',
14341434
except AssertionError as e:
14351435
print('Train Err: ctx %d vs ctx %d at %s'%(i, max_idx, name))
14361436
traceback.print_exc()
1437-
if raise_on_err: # pylint: disable=no-else-raise
1437+
if raise_on_err:
14381438
raise e
1439-
else:
1440-
print(str(e))
1439+
1440+
print(str(e))
14411441

14421442
return gt
14431443

@@ -1514,11 +1514,11 @@ def download(url, fname=None, dirname=None, overwrite=False, retries=5):
15141514
break
15151515
except Exception as e:
15161516
retries -= 1
1517-
if retries <= 0: # pylint: disable=no-else-raise
1517+
if retries <= 0:
15181518
raise e
1519-
else:
1520-
print("download failed, retrying, {} attempt{} left"
1521-
.format(retries, 's' if retries > 1 else ''))
1519+
1520+
print("download failed, retrying, {} attempt{} left"
1521+
.format(retries, 's' if retries > 1 else ''))
15221522
logging.info("downloaded %s into %s successfully", url, fname)
15231523
return fname
15241524

@@ -1661,7 +1661,7 @@ def get_mnist_iterator(batch_size, input_shape, num_parts=1, part_index=0):
16611661
"""
16621662

16631663
get_mnist_ubyte()
1664-
flat = False if len(input_shape) == 3 else True # pylint: disable=simplifiable-if-expression
1664+
flat = not bool(len(input_shape) == 3)
16651665

16661666
train_dataiter = mx.io.MNISTIter(
16671667
image="data/train-images-idx3-ubyte",

0 commit comments

Comments
 (0)