Sourcery refactored master branch#1
Conversation
| else: | ||
| redis_conn.delete(redis_key) | ||
| return "RESULT: {}".format(result) | ||
| redis_conn.delete(redis_key) | ||
| return "RESULT: {}".format(result) |
There was a problem hiding this comment.
Function wait refactored with the following changes:
- Remove unnecessary else after guard condition (
remove-unnecessary-else)
| payload = self.bytes() | ||
| else: | ||
| payload = self.bytes | ||
| payload = self.bytes() if callable(self.bytes) else self.bytes |
There was a problem hiding this comment.
Function Attachment.to_envelope_item refactored with the following changes:
- Replace if statement with if expression (
assign-if-exp)
| for errcls in self.options["ignore_errors"]: | ||
| # String types are matched against the type name in the | ||
| # exception only | ||
| if isinstance(errcls, string_types): | ||
| if errcls == full_name or errcls == type_name: | ||
| return True | ||
| else: | ||
| if issubclass(exc_info[0], errcls): | ||
| return True | ||
|
|
||
| return False | ||
| return any( | ||
| isinstance(errcls, string_types) | ||
| and errcls in [full_name, type_name] | ||
| or not isinstance(errcls, string_types) | ||
| and issubclass(exc_info[0], errcls) | ||
| for errcls in self.options["ignore_errors"] | ||
| ) |
There was a problem hiding this comment.
Function _Client._is_ignored_error refactored with the following changes:
- Merge duplicate blocks in conditional (
merge-duplicate-blocks) - Replace multiple comparisons of same variable with
inoperator (merge-comparisons) - Use any() instead of for loop (
use-any)
This removes the following comments ( why? ):
# String types are matched against the type name in the
# exception only
| if self._is_ignored_error(event, hint): | ||
| return False | ||
|
|
||
| return True | ||
| return not self._is_ignored_error(event, hint) |
There was a problem hiding this comment.
Function _Client._should_capture refactored with the following changes:
- Simplify conditional into return statement (
return-identity)
| items = [] | ||
| else: | ||
| items = list(items) | ||
| items = [] if items is None else list(items) |
There was a problem hiding this comment.
Function Envelope.__init__ refactored with the following changes:
- Replace if statement with if expression (
assign-if-exp)
| for item in set or (): | ||
| if item == name or name.startswith(item + "."): | ||
| return True | ||
| return False | ||
| return any(item == name or name.startswith(item + ".") for item in set or ()) |
There was a problem hiding this comment.
Function get_lines_from_file.get_source_context.filename_for_module.serialize_frame.handle_in_app_impl._module_in_set refactored with the following changes:
- Use any() instead of for loop (
use-any)
| version_tuple = tuple([int(part) for part in gevent.__version__.split(".")[:2]]) | ||
| version_tuple = tuple(int(part) for part in gevent.__version__.split(".")[:2]) |
There was a problem hiding this comment.
Function get_lines_from_file.get_source_context.filename_for_module.serialize_frame.handle_in_app_impl._is_contextvars_broken refactored with the following changes:
- Simplify conditional into return statement (
return-identity) - Replace unneeded comprehension with generator (
comprehension-to-generator)
This removes the following comments ( why? ):
# Gevent 20.9.0+
# Gevent 20.5.0+ or Python < 3.7
| # aiocontextvars is a PyPI package that ensures that the contextvars | ||
| # backport (also a PyPI package) works with asyncio under Python 3.6 | ||
| # | ||
| # Import it if available. | ||
| if sys.version_info < (3, 7): | ||
| # `aiocontextvars` is absolutely required for functional | ||
| # contextvars on Python 3.6. | ||
| try: | ||
| try: | ||
| if sys.version_info < (3, 7): | ||
| from aiocontextvars import ContextVar # noqa | ||
|
|
||
| return True, ContextVar | ||
| except ImportError: | ||
| pass | ||
| else: | ||
| # On Python 3.7 contextvars are functional. | ||
| try: | ||
| else: | ||
| from contextvars import ContextVar | ||
|
|
||
| return True, ContextVar | ||
| except ImportError: | ||
| pass | ||
|
|
||
| return True, ContextVar | ||
| except ImportError: | ||
| pass |
There was a problem hiding this comment.
Function get_lines_from_file.get_source_context.filename_for_module.serialize_frame.handle_in_app_impl._get_contextvars refactored with the following changes:
- Hoist repeated code outside conditional statement (
hoist-statement-from-if)
This removes the following comments ( why? ):
# On Python 3.7 contextvars are functional.
# backport (also a PyPI package) works with asyncio under Python 3.6
# aiocontextvars is a PyPI package that ensures that the contextvars
#
# Import it if available.
| integer_configured_timeout = integer_configured_timeout + 1 | ||
| integer_configured_timeout += 1 |
There was a problem hiding this comment.
Function get_lines_from_file.get_source_context.filename_for_module.serialize_frame.handle_in_app_impl.TimeoutThread.run refactored with the following changes:
- Replace assignment with augmented assignment (
aug-assign)
| integrations = dict( | ||
| (integration.identifier, integration) for integration in integrations or () | ||
| ) | ||
| integrations = { | ||
| integration.identifier: integration | ||
| for integration in integrations or () | ||
| } | ||
|
|
There was a problem hiding this comment.
Function _generate_default_integrations_iterator.iter_default_integrations.setup_integrations refactored with the following changes:
- Replace list(), dict() or set() with comprehension (
collection-builtin-to-comprehension) - Swap if/else branches (
swap-if-else-branches) - Remove unnecessary else after guard condition (
remove-unnecessary-else)
| self.__call__ = self._run_asgi3 # type: Callable[..., Any] | ||
| else: | ||
| self.__call__ = self._run_asgi2 | ||
| self.__call__ = self._run_asgi3 if _looks_like_asgi3(app) else self._run_asgi2 |
There was a problem hiding this comment.
Function SentryAsgiMiddleware.__init__ refactored with the following changes:
- Replace if statement with if expression (
assign-if-exp)
This removes the following comments ( why? ):
# type: Callable[..., Any]
| if key in headers: | ||
| headers[key] = headers[key] + ", " + value | ||
| else: | ||
| headers[key] = value | ||
| headers[key] = headers[key] + ", " + value if key in headers else value |
There was a problem hiding this comment.
Function SentryAsgiMiddleware._get_headers refactored with the following changes:
- Replace if statement with if expression (
assign-if-exp)
| else: | ||
| if aws_event.get("body", None): | ||
| # Unfortunately couldn't find a way to get structured body from AWS | ||
| # event. Meaning every body is unstructured to us. | ||
| request["data"] = AnnotatedValue("", {"rem": [["!raw", "x", 0, 0]]}) | ||
| elif aws_event.get("body", None): | ||
| # Unfortunately couldn't find a way to get structured body from AWS | ||
| # event. Meaning every body is unstructured to us. | ||
| request["data"] = AnnotatedValue("", {"rem": [["!raw", "x", 0, 0]]}) |
There was a problem hiding this comment.
Function _make_request_event_processor.event_processor refactored with the following changes:
- Merge else clause's nested if statement into elif (
merge-else-if-into-elif)
| url = ( | ||
| return ( |
There was a problem hiding this comment.
Function _get_cloudwatch_logs_url refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable)
| if integration is not None and integration.propagate_traces: | ||
| with hub.start_span(op="celery.submit", description=args[0].name) as span: | ||
| with capture_internal_exceptions(): | ||
| headers = dict(hub.iter_trace_propagation_headers(span)) | ||
|
|
||
| if headers: | ||
| # Note: kwargs can contain headers=None, so no setdefault! | ||
| # Unsure which backend though. | ||
| kwarg_headers = kwargs.get("headers") or {} | ||
| kwarg_headers.update(headers) | ||
|
|
||
| # https://github.com/celery/celery/issues/4875 | ||
| # | ||
| # Need to setdefault the inner headers too since other | ||
| # tracing tools (dd-trace-py) also employ this exact | ||
| # workaround and we don't want to break them. | ||
| kwarg_headers.setdefault("headers", {}).update(headers) | ||
| kwargs["headers"] = kwarg_headers | ||
| if integration is None or not integration.propagate_traces: | ||
| return f(*args, **kwargs) | ||
| with hub.start_span(op="celery.submit", description=args[0].name) as span: | ||
| with capture_internal_exceptions(): | ||
| headers = dict(hub.iter_trace_propagation_headers(span)) | ||
|
|
||
| if headers: | ||
| # Note: kwargs can contain headers=None, so no setdefault! | ||
| # Unsure which backend though. | ||
| kwarg_headers = kwargs.get("headers") or {} | ||
| kwarg_headers.update(headers) | ||
|
|
||
| # https://github.com/celery/celery/issues/4875 | ||
| # | ||
| # Need to setdefault the inner headers too since other | ||
| # tracing tools (dd-trace-py) also employ this exact | ||
| # workaround and we don't want to break them. | ||
| kwarg_headers.setdefault("headers", {}).update(headers) | ||
| kwargs["headers"] = kwarg_headers | ||
|
|
||
| return f(*args, **kwargs) | ||
| else: |
There was a problem hiding this comment.
Function _wrap_apply_async.apply_async refactored with the following changes:
- Swap if/else branches (
swap-if-else-branches) - Remove unnecessary else after guard condition (
remove-unnecessary-else)
| # type: (str) -> str | ||
| if isinstance(template_name, (list, tuple)): | ||
| if template_name: | ||
| return "[{}, ...]".format(template_name[0]) | ||
| else: | ||
| if not isinstance(template_name, (list, tuple)): | ||
| return template_name | ||
| if template_name: | ||
| return "[{}, ...]".format(template_name[0]) |
There was a problem hiding this comment.
Function _get_template_name_description refactored with the following changes:
- Swap if/else branches (
swap-if-else-branches) - Remove unnecessary else after guard condition (
remove-unnecessary-else)
This removes the following comments ( why? ):
# type: (str) -> str
| rv = [] | ||
|
|
||
| # On Exception worker will call sys.exit(-1), so we can ignore SystemExit and similar errors | ||
| for exc_type, exc_value, tb in walk_exception_chain(exc_info): | ||
| if exc_type not in (SystemExit, EOFError, ConnectionResetError): | ||
| rv.append( | ||
| single_exception_from_error_tuple( | ||
| exc_type, exc_value, tb, client_options, mechanism | ||
| ) | ||
| ) |
There was a problem hiding this comment.
Function _capture_exception refactored with the following changes:
- Convert for loop into list comprehension (
list-comprehension)
This removes the following comments ( why? ):
# On Exception worker will call sys.exit(-1), so we can ignore SystemExit and similar errors
| assert not any(item.data_category == "error" for item in envelope.items) | ||
| assert not any(item.get_event() is not None for item in envelope.items) | ||
| assert all(item.data_category != "error" for item in envelope.items) | ||
| assert all(item.get_event() is None for item in envelope.items) |
There was a problem hiding this comment.
Function monkeypatch_test_transport.check_envelope refactored with the following changes:
- Invert any/all to simplify comparisons (
invert-any-all)
| if self.type: | ||
| if not isinstance(test_obj, self.type): | ||
| return False | ||
| if self.type and not isinstance(test_obj, self.type): | ||
| return False |
There was a problem hiding this comment.
Function object_described_by_matcher.ObjectDescribedBy.__eq__ refactored with the following changes:
- Merge nested if conditions (
merge-nested-ifs)
| if hint: | ||
| if "exc_info" in hint: | ||
| error = hint["exc_info"][1] | ||
| errors.add(error) | ||
| if hint and "exc_info" in hint: | ||
| error = hint["exc_info"][1] | ||
| errors.add(error) |
There was a problem hiding this comment.
Function capture_exceptions.inner.capture_event refactored with the following changes:
- Merge nested if conditions (
merge-nested-ifs)
| def middleware(request): | ||
| response = get_response(request) | ||
| return response | ||
| return get_response(request) |
There was a problem hiding this comment.
Function simple_middleware.middleware refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable)
| assert not any( | ||
| crumb["message"] == "LOL" for crumb in event["breadcrumbs"]["values"] | ||
| assert all( | ||
| crumb["message"] != "LOL" for crumb in event["breadcrumbs"]["values"] | ||
| ) | ||
|
|
There was a problem hiding this comment.
Function test_logging_defaults refactored with the following changes:
- Invert any/all to simplify comparisons (
invert-any-all)
| def jobResult(self): # noqa: N802 | ||
| result = MockJobResult() | ||
| return result | ||
| return MockJobResult() |
There was a problem hiding this comment.
Function test_sentry_listener_on_job_end.MockJobEnd.jobResult refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable)
| stageinf = StageInfo() | ||
| return stageinf | ||
| return StageInfo() |
There was a problem hiding this comment.
Function test_sentry_listener_on_stage_submitted.MockStageSubmitted.stageInfo refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable)
| request = event["request"] | ||
| host = request["headers"]["Host"] | ||
| assert event["request"] == { | ||
| assert request == { |
There was a problem hiding this comment.
Function test_basic refactored with the following changes:
- Use previously assigned local variable (
use-assigned-variable)
| assert server_tx["request"] == { | ||
| assert request == { |
There was a problem hiding this comment.
Function test_transactions refactored with the following changes:
- Use previously assigned local variable (
use-assigned-variable)
| else: | ||
| event_id = last_event_id() | ||
| data = TrytondUserError(str(event_id), str(e)) | ||
| return app.make_response(request, data) | ||
| event_id = last_event_id() | ||
| data = TrytondUserError(str(event_id), str(e)) | ||
| return app.make_response(request, data) |
There was a problem hiding this comment.
Function test_rpc_error_page._ refactored with the following changes:
- Remove unnecessary else after guard condition (
remove-unnecessary-else)
| assert trace1["transaction"] == "hi" | ||
| else: | ||
| trace1, message, trace2 = events | ||
|
|
||
| assert trace1["transaction"] == "hi" |
There was a problem hiding this comment.
Function test_continue_from_headers refactored with the following changes:
- Hoist repeated code outside conditional statement (
hoist-statement-from-if)
Sourcery Code Quality Report✅ Merging this PR will increase code quality in the affected files by 0.25%.
Here are some functions in these files that still need a tune-up:
Legend and ExplanationThe emojis denote the absolute quality of the code:
The 👍 and 👎 indicate whether the quality has improved or gotten worse with this pull request. Please see our documentation here for details on how these metrics are calculated. We are actively working on this report - lots more documentation and extra metrics to come! Help us improve this quality report! |
Branch
masterrefactored by Sourcery.If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.
See our documentation here.
Run Sourcery locally
Reduce the feedback loop during development by using the Sourcery editor plugin:
Review changes via command line
To manually merge these changes, make sure you're on the
masterbranch, then run:Help us improve this pull request!