Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Address remaining flake8-simplify lints that could not be done on Python 2 #314

Merged
merged 4 commits into from
Feb 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,6 @@ ignore=
E203,
W503,
W504,
# Use 'class Klass:' instead of 'class Klass(object), can't do this on Python 2
SIM120,
# use yield from, can't do this on Python 2
SIM104,
# use contextlib.suppress, can't do this on Python 2
SIM105,
SIM106,
SIM110,
SIM111,
Expand Down
9 changes: 4 additions & 5 deletions inbox/actions/backends/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
""" Operations for syncing back local datastore changes to
generic IMAP providers.
"""
import contextlib
from collections import defaultdict
from imaplib import IMAP4

Expand Down Expand Up @@ -149,12 +150,10 @@ def remote_delete_folder(crispin_client, account_id, category_id):
return
display_name = category.display_name

try:
with contextlib.suppress(IMAP4.error):
# IMAP4.error: Folder has already been deleted on remote. Treat delete
# as no-op.
crispin_client.conn.delete_folder(display_name)
except IMAP4.error:
# Folder has already been deleted on remote. Treat delete as
# no-op.
pass

# TODO @karim: Make the main sync loop detect folder renames
# more accurately, and get rid of this.
Expand Down
9 changes: 4 additions & 5 deletions inbox/actions/backends/gmail.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
""" Operations for syncing back local datastore changes to Gmail. """

import contextlib
from imaplib import IMAP4

import imapclient
Expand Down Expand Up @@ -62,12 +63,10 @@ def remote_delete_label(crispin_client, account_id, category_id):
return
display_name = category.display_name

try:
with contextlib.suppress(IMAP4.error):
# IMAP4.error: Label has already been deleted on remote. Treat delete
# as no-op.
crispin_client.conn.delete_folder(display_name)
except IMAP4.error:
# Label has already been deleted on remote. Treat delete as
# no-op.
pass

# TODO @karim --- the main sync loop has a hard time detecting
# Gmail renames because of a Gmail issue (see https://github.com/nylas/sync-engine/blob/c99656df3c048faf7951e54d74cb5ef9d7dc3c97/inbox/mailsync/gc.py#L146 for more details).
Expand Down
2 changes: 1 addition & 1 deletion inbox/api/kellogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ def _get_lowercase_class_name(obj):
return resp


class APIEncoder(object):
class APIEncoder:
"""
Provides methods for serializing Nylas objects. If the optional
namespace_public_id parameter is passed, it will be bound and used instead
Expand Down
8 changes: 4 additions & 4 deletions inbox/api/ns_api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import base64
import contextlib
import itertools
import json
import os
Expand Down Expand Up @@ -124,11 +125,10 @@
from inbox.util.misc import imap_folder_path
from inbox.util.stats import statsd_client

try:
with contextlib.suppress(ImportError):
# ImportError: Only important for EAS search failures, so shouldn't trigger
# test failure.
from inbox.util.eas.codes import STORE_STATUS_CODES
except ImportError:
# Only important for EAS search failures, so shouldn't trigge test fail
pass


from inbox.logging import get_logger
Expand Down
5 changes: 2 additions & 3 deletions inbox/api/validation.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Utilities for validating user input to the API."""
import contextlib
from builtins import str

import arrow
Expand Down Expand Up @@ -129,10 +130,8 @@ def valid_category_type(category_type, rule):

def timestamp(value, key):
try:
try:
with contextlib.suppress(ValueError):
value = float(value)
except ValueError:
pass

return arrow.get(value).datetime
except ValueError:
Expand Down
2 changes: 1 addition & 1 deletion inbox/auth/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def handler_from_provider(provider_name):
)


class AuthHandler(object):
class AuthHandler:
def create_account(self, account_data):
"""
Create a new account with the given subclass-specific account data.
Expand Down
2 changes: 1 addition & 1 deletion inbox/auth/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@


@attr.s
class GenericAccountData(object):
class GenericAccountData:
email = attr.ib()

imap_server_host = attr.ib()
Expand Down
2 changes: 1 addition & 1 deletion inbox/auth/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@


@attr.s
class GoogleAccountData(object):
class GoogleAccountData:
email = attr.ib()

secret_type = attr.ib()
Expand Down
2 changes: 1 addition & 1 deletion inbox/auth/microsoft.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@


@attr.s
class MicrosoftAccountData(object):
class MicrosoftAccountData:
email = attr.ib()

secret_type = attr.ib()
Expand Down
5 changes: 2 additions & 3 deletions inbox/client/client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextlib
import json
import sys
from os import environ
Expand Down Expand Up @@ -67,10 +68,8 @@ def _validate(response):
)
)

try:
with contextlib.suppress(ValueError, TypeError):
data = json.loads(data) if data else None
except (ValueError, TypeError):
pass

if status_code == 200:
return response
Expand Down
7 changes: 2 additions & 5 deletions inbox/client/restful_model_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
CHUNK_SIZE = 50


class RestfulModelCollection(object):
class RestfulModelCollection:
def __init__(self, cls, api, filter=None, offset=0, **filters):
filter = filter or {}
filters.update(filter)
Expand All @@ -25,11 +25,8 @@ def items(self):
offset = self.filters["offset"]
while True:
items = self._get_model_collection(offset, CHUNK_SIZE)
if not items:
break

for item in items:
yield item
yield from items

if len(items) < CHUNK_SIZE:
break
Expand Down
2 changes: 1 addition & 1 deletion inbox/contacts/carddav.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def supports_carddav(url):
raise Exception("URL is not a CardDAV resource")


class CardDav(object):
class CardDav:
""" NOTE: Only supports iCloud for now """

def __init__(self, email_address, password, base_url):
Expand Down
2 changes: 1 addition & 1 deletion inbox/contacts/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
SOURCE_APP_NAME = "Nylas Sync Engine"


class GoogleContactsProvider(object):
class GoogleContactsProvider:
"""
A utility class to fetch and parse Google contact data for the specified
account using the Google Contacts API.
Expand Down
8 changes: 4 additions & 4 deletions inbox/contacts/icloud.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Provide iCloud contacts"""
from __future__ import absolute_import

import contextlib

import lxml.etree as ET

from inbox.contacts.carddav import supports_carddav
Expand All @@ -17,7 +19,7 @@
ICLOUD_CONTACTS_URL = "https://contacts.icloud.com"


class ICloudContactsProvider(object):
class ICloudContactsProvider:
"""
Base class to fetch and parse iCloud contacts
"""
Expand All @@ -39,10 +41,8 @@ def _vCard_raw_to_contact(self, cardstring):

def _x(key): # Ugly parsing helper for ugly formats
if key in card:
try:
with contextlib.suppress(IndexError):
return card[key][0][0]
except IndexError:
pass

# Skip contact groups for now
if _x("X-ADDRESSBOOKSERVER-KIND") == "group":
Expand Down
2 changes: 1 addition & 1 deletion inbox/contacts/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def cloudsearch_contact_repr(contact):
}


class ContactSearchClient(object):
class ContactSearchClient:
""" Search client that talks to AWS CloudSearch (or a compatible API). """

def __init__(self, namespace_id):
Expand Down
6 changes: 2 additions & 4 deletions inbox/contacts/vcard.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from __future__ import absolute_import, print_function

import base64
import contextlib
import logging
import sys
from builtins import range
Expand Down Expand Up @@ -172,12 +173,9 @@ def vcard_from_vobject(vcard):
property_name = line.name
property_value = line.value

try:
with contextlib.suppress(AttributeError):
if line.ENCODING_paramlist == [u"b"] or line.ENCODING_paramlist == [u"B"]:
property_value = base64.b64encode(line.value)

except AttributeError:
pass
if isinstance(property_value, list):
property_value = (",").join(property_value)

Expand Down
4 changes: 2 additions & 2 deletions inbox/crispin.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def writable_connection_pool(account_id, pool_size=1):
return _get_connection_pool(account_id, pool_size, _writable_pool_map, False)


class CrispinConnectionPool(object):
class CrispinConnectionPool:
"""
Connection pool for Crispin clients.

Expand Down Expand Up @@ -309,7 +309,7 @@ def _exc_callback(exc):
)


class CrispinClient(object):
class CrispinClient:
"""
Generic IMAP client wrapper.

Expand Down
2 changes: 1 addition & 1 deletion inbox/events/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
WATCH_EVENTS_URL = "https://www.googleapis.com/calendar/v3/calendars/{}/events/watch"


class GoogleEventsProvider(object):
class GoogleEventsProvider:
"""
A utility class to fetch and parse Google calendar data for the
specified account using the Google Calendar API.
Expand Down
6 changes: 3 additions & 3 deletions inbox/heartbeat/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def wrapper(*args, **kwargs):
return wrapper


class HeartbeatStatusKey(object):
class HeartbeatStatusKey:
def __init__(self, account_id, folder_id):
self.account_id = account_id
self.folder_id = folder_id
Expand Down Expand Up @@ -57,7 +57,7 @@ def from_string(cls, string_key):
return cls(account_id, folder_id)


class HeartbeatStatusProxy(object):
class HeartbeatStatusProxy:
def __init__(
self,
account_id,
Expand Down Expand Up @@ -93,7 +93,7 @@ def clear(self):
self.store.remove_folders(self.account_id, self.folder_id, self.device_id)


class HeartbeatStore(object):
class HeartbeatStore:
""" Store that proxies requests to Redis with handlers that also
update indexes and handle scanning through results. """

Expand Down
2 changes: 1 addition & 1 deletion inbox/ignition.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def receive_checkin(dbapi_connection, connection_record):
return engine


class EngineManager(object):
class EngineManager:
def __init__(self, databases, users, include_disabled=False):
self.engines = {}
self._engine_zones = {}
Expand Down
6 changes: 3 additions & 3 deletions inbox/instrumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
LOGGING_INTERVAL = 60


class ProfileCollector(object):
class ProfileCollector:
"""A simple stack sampler for low-overhead CPU profiling: samples the call
stack every `interval` seconds and keeps track of counts by frame. Because
this uses signals, it only works on the main thread."""
Expand Down Expand Up @@ -74,7 +74,7 @@ def reset(self):
self._stack_counts = collections.defaultdict(int)


class GreenletTracer(object):
class GreenletTracer:
"""Log if a greenlet blocks the event loop for too long, and optionally log
statistics on time spent in individual greenlets.

Expand Down Expand Up @@ -286,7 +286,7 @@ def _notify_greenlet_blocked(self, active_greenlet, current_time):
MAX_BLOCKING_TIME = 5


class Tracer(object):
class Tracer:
"""Log if a greenlet blocks the event loop for too long, and optionally log
statistics on time spent in individual greenlets.

Expand Down
9 changes: 3 additions & 6 deletions inbox/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""
from __future__ import absolute_import

import contextlib
import logging
import logging.handlers
import os
Expand Down Expand Up @@ -345,17 +346,13 @@ def create_error_log_context(exc_info):
out["error_code"] = exc_value.code

if hasattr(exc_value, "args") and hasattr(exc_value.args, "__getitem__"):
try:
with contextlib.suppress(IndexError):
out["error_message"] = exc_value.args[0]
except IndexError:
pass

try:
with contextlib.suppress(Exception):
if exc_tb:
tb = safe_format_exception(exc_type, exc_value, exc_tb)
if tb:
out["error_traceback"] = tb
except Exception:
pass

return out
3 changes: 1 addition & 2 deletions inbox/mailsync/backends/gmail.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,8 +491,7 @@ def expand_uids_to_download(self, crispin_client, uids, metadata):
if g_thrid != g_msgid:
uids = set(uids).union(crispin_client.expand_thread(g_thrid))
metadata.update(crispin_client.g_metadata(uids))
for uid in sorted(uids, reverse=True):
yield uid
yield from sorted(uids, reverse=True)

def batch_download_uids(
self,
Expand Down
Loading