Skip to content
Snippets Groups Projects
Commit ddc72f46 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

refactor thanks to CodeClimate

parent fe6a7c6d
No related branches found
No related tags found
No related merge requests found
...@@ -254,29 +254,31 @@ def build_structure(struct: tp.Union[tuple, list, dict], ...@@ -254,29 +254,31 @@ def build_structure(struct: tp.Union[tuple, list, dict],
""" """
if not nested_call: if not nested_call:
v = build_structure(struct, argument, None, True) v = build_structure(struct, argument, None, True)
return final_operator(v) f = final_operator(v)
from satella.coding.structures import HashableWrapper
if isinstance(struct, tp.MutableMapping):
new_dict = {}
for key, value in struct.items():
key = build_structure(key, argument, None, True)
value = build_structure(value, argument, None, True)
new_dict[key] = value
return new_dict
elif isinstance(struct, tp.Sequence):
new_seq = []
for elem in struct:
if isinstance(elem, PredicateClass):
elem = elem(argument)
else:
elem = build_structure(elem, argument, None, True)
new_seq.append(elem)
return struct.__class__(new_seq)
elif isinstance(struct, HashableWrapper):
obj = getattr(struct, '_Proxy__obj')
return build_structure(obj, argument, None, True)
elif isinstance(struct, PredicateClass):
return struct(argument)
else: else:
return struct from satella.coding.structures import HashableWrapper
if isinstance(struct, tp.MutableMapping):
new_dict = {}
for key, value in struct.items():
key = build_structure(key, argument, None, True)
value = build_structure(value, argument, None, True)
new_dict[key] = value
f = new_dict
break
elif isinstance(struct, tp.Sequence):
new_seq = []
for elem in struct:
if isinstance(elem, PredicateClass):
elem = elem(argument)
else:
elem = build_structure(elem, argument, None, True)
new_seq.append(elem)
f = struct.__class__(new_seq)
elif isinstance(struct, HashableWrapper):
obj = getattr(struct, '_Proxy__obj')
f = build_structure(obj, argument, None, True)
elif isinstance(struct, PredicateClass):
f = struct(argument)
else:
f = struct
return f
...@@ -188,14 +188,15 @@ class SparseMatrix(tp.Generic[T]): ...@@ -188,14 +188,15 @@ class SparseMatrix(tp.Generic[T]):
:param row_no: row number, numbered from 0 :param row_no: row number, numbered from 0
""" """
if row_no not in self.rows_dict: # check so as to avoid adding new entries if row_no not in self.rows_dict: # check so as to avoid adding new entries
return [None] * self.no_cols output = [None] * self.no_cols
cols = self.rows_dict[row_no] else:
output = [] cols = self.rows_dict[row_no]
for i in range(self.no_cols): output = []
if i in cols: for i in range(self.no_cols):
output.append(cols[i]) if i in cols:
else: output.append(cols[i])
output.append(None) else:
output.append(None)
return output return output
def shoot(self) -> 'SparseMatrix': def shoot(self) -> 'SparseMatrix':
...@@ -283,21 +284,24 @@ class SparseMatrix(tp.Generic[T]): ...@@ -283,21 +284,24 @@ class SparseMatrix(tp.Generic[T]):
col, row = self._sanitize_key(item) col, row = self._sanitize_key(item)
if col is Ellipsis and row is Ellipsis: if col is Ellipsis and row is Ellipsis:
return list(self) v = list(self)
elif col is Ellipsis: elif col is Ellipsis:
return [self[col_no, row] for col_no in range(self.no_cols)] v = [self[col_no, row] for col_no in range(self.no_cols)]
elif row is Ellipsis: elif row is Ellipsis:
return [self[col, row_no] for row_no in range(self.no_rows)] v = [self[col, row_no] for row_no in range(self.no_rows)]
else: else:
if row >= self.no_rows: if row >= self.no_rows:
raise IndexError() raise IndexError()
elif col >= self.no_cols: elif col >= self.no_cols:
raise IndexError() raise IndexError()
if row not in self.rows_dict: # check so as to avoid adding new entries if row not in self.rows_dict: # check so as to avoid adding new entries
return None v = None
if col not in self.rows_dict[row]: elif col not in self.rows_dict[row]:
return None v = None
return self.rows_dict[row][col] else:
v = self.rows_dict[row][col]
return v
@silence_excs(TypeError, returns=0) @silence_excs(TypeError, returns=0)
def _calculate_column_count(self) -> int: def _calculate_column_count(self) -> int:
...@@ -321,10 +325,7 @@ class SparseMatrix(tp.Generic[T]): ...@@ -321,10 +325,7 @@ class SparseMatrix(tp.Generic[T]):
del self[col, row_no] del self[col, row_no]
else: else:
# Check if the element is there # Check if the element is there
if row not in self.rows_dict: if (row not in self.rows_dict) or (col not in self.rows_dict[row]):
return
if col not in self.rows_dict[row]:
return return
del self.rows_dict[row][col] del self.rows_dict[row][col]
......
...@@ -194,6 +194,7 @@ class SyncableDroppable(RMonitor, tp.Generic[K, V]): ...@@ -194,6 +194,7 @@ class SyncableDroppable(RMonitor, tp.Generic[K, V]):
# We no longer have ANY data # We no longer have ANY data
self.start_entry = self.stop_entry = None self.start_entry = self.stop_entry = None
return True return True
finally: finally:
try_close(iterator) try_close(iterator)
return False return False
......
...@@ -19,22 +19,23 @@ def jsonify(data: tp.Any) -> tp.Optional[tp.Union[str, int, float, list, dict]]: ...@@ -19,22 +19,23 @@ def jsonify(data: tp.Any) -> tp.Optional[tp.Union[str, int, float, list, dict]]:
:return: JSON-able data :return: JSON-able data
""" """
if data is None: if data is None:
return None v = None
elif isinstance(data, (int, float, str)): elif isinstance(data, (int, float, str)):
return data v = data
elif isinstance(data, enum.Enum): elif isinstance(data, enum.Enum):
return data.value v = data.value
elif isinstance(data, JSONAble): elif isinstance(data, JSONAble):
return jsonify(data.to_json()) v = jsonify(data.to_json())
elif isinstance(data, tp.Mapping): elif isinstance(data, tp.Mapping):
new_mapping = {} new_mapping = {}
for key in data: for key in data:
new_mapping[jsonify(key)] = jsonify(data[key]) new_mapping[jsonify(key)] = jsonify(data[key])
return new_mapping v = new_mapping
elif isinstance(data, (tp.Iterable, tp.Iterator)): elif isinstance(data, (tp.Iterable, tp.Iterator)):
return [jsonify(elem) for elem in data] v = [jsonify(elem) for elem in data]
else: else:
try: try:
return str(data) v = str(data)
except TypeError: except TypeError:
return repr(data) v = repr(data)
return v
...@@ -30,30 +30,31 @@ class JSONEncoder(json.JSONEncoder): ...@@ -30,30 +30,31 @@ class JSONEncoder(json.JSONEncoder):
def default(self, o: tp.Any) -> Jsonable: def default(self, o: tp.Any) -> Jsonable:
if hasattr(o, 'to_json'): if hasattr(o, 'to_json'):
return o.to_json() v = o.to_json()
elif isinstance(o, (int, float, str, NoneType)): elif isinstance(o, (int, float, str, NoneType)):
return o v = o
elif isinstance(o, enum.Enum): elif isinstance(o, enum.Enum):
return o.value v = o.value
elif isinstance(o, (list, tuple)): elif isinstance(o, (list, tuple)):
return [self.default(v) for v in o] v = [self.default(v) for v in o]
elif isinstance(o, dict): elif isinstance(o, dict):
return {self.default(k): self.default(v) for k, v in o.items()} v = {self.default(k): self.default(v) for k, v in o.items()}
else:
try:
return super().default(o)
except TypeError:
dct = {}
try: try:
for k, v in o.__dict__.items(): v = super().default(o)
dct[k] = self.default(v) except TypeError:
except AttributeError: # o has no attribute '__dict__', try with slots dct = {}
try: try:
for slot in o.__slots__: for k, v in o.__dict__.items():
dct[slot] = self.default(getattr(o, slot)) dct[k] = self.default(v)
except AttributeError: # it doesn't have __slots__ either? except AttributeError: # o has no attribute '__dict__', try with slots
return '<an instance of %s>' % (o.__class__.__name__,) try:
return dct for slot in o.__slots__:
dct[slot] = self.default(getattr(o, slot))
except AttributeError: # it doesn't have __slots__ either?
v = '<an instance of %s>' % (o.__class__.__name__,)
v = dct
return v
def json_encode(x: tp.Any) -> str: def json_encode(x: tp.Any) -> str:
...@@ -109,10 +110,11 @@ def read_json_from_file(path: str) -> JSONAble: ...@@ -109,10 +110,11 @@ def read_json_from_file(path: str) -> JSONAble:
try: try:
import ujson import ujson
with open(path, 'r') as f_in: with open(path, 'r') as f_in:
return ujson.load(f_in) v = ujson.load(f_in)
except ImportError: except ImportError:
with open(path, 'r') as f_in: with open(path, 'r') as f_in:
try: try:
return json.load(f_in) v = json.load(f_in)
except json.decoder.JSONDecodeError as e: except json.decoder.JSONDecodeError as e:
raise ValueError(str(e)) raise ValueError(str(e))
return v
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment