diff --git a/satella/cassandra/future.py b/satella/cassandra/future.py index 8ffa1d1a96515155a48a1f53137be504407e28d2..b0316ce79fdedd83aae6d252e9144d68e526f3c0 100644 --- a/satella/cassandra/future.py +++ b/satella/cassandra/future.py @@ -18,6 +18,6 @@ def wrap_future(future: ResponseFuture) -> Future: fut = Future() fut.set_running_or_notify_cancel() - future.add_callback(lambda result: fut.set_result(result)) - future.add_errback(lambda exception: fut.set_exception(exception)) + future.add_callback(fut.set_result) + future.add_errback(fut.set_exception) return fut diff --git a/satella/cassandra/parallel.py b/satella/cassandra/parallel.py index 05ad59cda32051b685f2b776ca96d5ac5688f425..fc8def3e5938d3368e8e84bb2c6eda8badbe7818 100644 --- a/satella/cassandra/parallel.py +++ b/satella/cassandra/parallel.py @@ -37,7 +37,7 @@ def parallel_for(cursor, query: tp.Union[tp.List[str], str, 'Statement', tp.List """ warnings.warn('This is deprecated and will be removed in Satella 3.0', DeprecationWarning) try: - from cassandra.query import Statement + from cassandra.query import Statement # pylint: disable=import-outside-toplevel query_classes = (str, Statement) except ImportError: query_classes = str @@ -46,11 +46,8 @@ def parallel_for(cursor, query: tp.Union[tp.List[str], str, 'Statement', tp.List query = itertools.repeat(query) futures = [] - for query, args in zip(query, arguments): - if args is None: - future = cursor.execute_async(query) - else: - future = cursor.execute_async(query, args) + for loc_query, args in zip(query, arguments): + future = cursor.execute_async(loc_query) if args is None else cursor.execute_async(loc_query, args) futures.append(future) for future in futures: diff --git a/satella/coding/misc.py b/satella/coding/misc.py index 45fc3c11625872e66d6d854ef69f9c709490270e..05962dbf19b97f9767aa52f9644d83bde28a545f 100644 --- a/satella/coding/misc.py +++ b/satella/coding/misc.py @@ -168,8 +168,7 @@ def chain_callables(callable1: tp.Callable, callable2: tp.Callable) -> tp.Callab try: res = callable2(res) except TypeError as e: - if 'positional arguments but' in e.args[0] \ - and 'was given' in e.args[0] and 'takes' in e.args[0]: + if 'positional arguments but' in e.args[0] and 'was given' in e.args[0] and 'takes' in e.args[0]: res = callable2() else: raise @@ -195,8 +194,7 @@ def source_to_function(src: tp.Union[tp.Callable, str]) -> tp.Callable[[tp.Any], q = dict(globals()) exec('_precond = lambda x: ' + src, q) return q['_precond'] - else: - return src + return src def update_attr_if_none(obj: object, attr: str, value: tp.Any, @@ -224,14 +222,13 @@ def update_attr_if_none(obj: object, attr: str, value: tp.Any, if val is None: setattr(obj, attr, value) except AttributeError: - if on_attribute_error: - setattr(obj, attr, value) - else: + if not on_attribute_error: raise + setattr(obj, attr, value) return obj -class _BLANK: +class _BLANK: # pylint: disable=too-few-public-methods pass @@ -292,7 +289,7 @@ def _get_arguments(function: tp.Callable, special_behaviour: bool, *args, **kwar args = list(reversed(args)) arguments_left = set(param.name for param in params) - while len(positionals): + while positionals: arg = positionals.pop() arg_kind = arg.kind arg_name = arg.name @@ -321,30 +318,28 @@ def _get_arguments(function: tp.Callable, special_behaviour: bool, *args, **kwar keyword_name = keyword.name if keyword.kind == Parameter.VAR_KEYWORD and not special_behaviour: local_vars[keyword_name] = kwargs - else: + continue + try: + v = kwargs.pop(keyword_name) + except KeyError: try: - v = kwargs.pop(keyword_name) - except KeyError: - try: - if Parameter.empty == keyword.default: - if special_behaviour: - v = None - else: - raise TypeError('Not enough keyword arguments') - else: - v = keyword.default - except (AttributeError, TypeError): - continue # comparison was impossible + if Parameter.empty == keyword.default: + if not special_behaviour: + raise TypeError('Not enough keyword arguments') + v = None + else: + v = keyword.default + except (AttributeError, TypeError): + continue # comparison was impossible - local_vars[keyword_name] = v + local_vars[keyword_name] = v for param in params: param_name = param.name if param_name not in local_vars: - if special_behaviour: - local_vars[param_name] = None - else: + if not special_behaviour: raise TypeError('Not enough keyword arguments') + local_vars[param_name] = None return local_vars diff --git a/satella/coding/recast_exceptions.py b/satella/coding/recast_exceptions.py index 6c2b34b2f7ef44b4d9ce5663519363abee75ed41..3b105ba2d4e066947761887cbc4daf8fe6959a7a 100644 --- a/satella/coding/recast_exceptions.py +++ b/satella/coding/recast_exceptions.py @@ -31,8 +31,7 @@ def silence_excs(*exc_types: ExceptionClassType, returns=None, :raises ValueError: you gave both returns and returns_factory. You can only pass one of them! """ - return rethrow_as(exc_types, None, returns=returns, - returns_factory=returns_factory) + return rethrow_as(exc_types, None, returns=returns, returns_factory=returns_factory) class log_exceptions: @@ -59,8 +58,7 @@ class log_exceptions: log on all exceptions :param swallow_exception: if True, exception will be swallowed """ - __slots__ = ('logger', 'severity', 'format_string', 'locals', 'exc_types', - 'swallow_exception') + __slots__ = 'logger', 'severity', 'format_string', 'locals', 'exc_types', 'swallow_exception' def __init__(self, logger: logging.Logger, severity: int = logging.ERROR, @@ -81,24 +79,20 @@ class log_exceptions: def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: - if not self.analyze_exception(exc_val, (), {}): - return False - else: - return self.swallow_exception + return False if not self.analyze_exception(exc_val, (), {}) else self.swallow_exception return False def analyze_exception(self, e, args, kwargs) -> bool: """Return whether the exception has been logged""" - if isinstance(e, self.exc_types): - format_dict = {'args': args, - 'kwargs': kwargs} - if self.locals is not None: - format_dict.update(self.locals) - format_dict['e'] = e - self.logger.log(self.severity, self.format_string.format(**format_dict), - exc_info=e) - return True - return False + if not isinstance(e, self.exc_types): + return False + format_dict = {'args': args, 'kwargs': kwargs} + if self.locals is not None: + format_dict.update(self.locals) + format_dict['e'] = e + self.logger.log(self.severity, self.format_string.format(**format_dict), + exc_info=e) + return True def __call__(self, fun): if inspect.isgeneratorfunction(fun): @@ -107,10 +101,8 @@ class log_exceptions: # noinspection PyBroadException try: yield from fun(*args, **kwargs) - except Exception as e: - if not self.analyze_exception(e, args, kwargs): - raise - elif not self.swallow_exception: + except Exception as e: # pylint: disable=broad-except + if not self.analyze_exception(e, args, kwargs) or not self.swallow_exception: raise return inner @@ -120,10 +112,8 @@ class log_exceptions: # noinspection PyBroadException try: return fun(*args, **kwargs) - except Exception as e: - if not self.analyze_exception(e, args, kwargs): - raise - elif not self.swallow_exception: + except Exception as e: # pylint: disable=broad-except + if not self.analyze_exception(e, args, kwargs) or not self.swallow_exception: raise return inner @@ -175,12 +165,10 @@ class reraise_as: def inner(*args, **kwargs): try: return fun(*args, **kwargs) - except Exception as e: - if isinstance(e, self.source): - if self.target_exc is not None: - raise self.target_exc(*self.args, **self.kwargs) from e - else: - raise + except Exception as e: # pylint: disable=broad-except + if isinstance(e, self.source) and self.target_exc is not None: + raise self.target_exc(*self.args, **self.kwargs) from e + raise return inner @@ -234,8 +222,7 @@ class rethrow_as: is used as as decorator :raises ValueError: you specify both returns and returns_factory """ - __slots__ = 'mapping', 'exception_preprocessor', 'returns', '__exception_remapped', \ - 'returns_factory' + __slots__ = 'mapping', 'exception_preprocessor', 'returns', '__exception_remapped', 'returns_factory' def __init__(self, *pairs: ExceptionList, exception_preprocessor: tp.Optional[tp.Callable[[Exception], str]] = repr, @@ -305,8 +292,7 @@ def raises_exception(exc_class: tp.Union[ExceptionClassType, tp.Tuple[ExceptionC clb() except exc_class: return True - else: - return False + return False def catch_exception(exc_class: tp.Union[ExceptionClassType, tp.Tuple[ExceptionClassType, ...]],