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

Add some type annotations #988

Merged
merged 7 commits into from
Dec 12, 2024
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
2 changes: 1 addition & 1 deletion bin/create-event-contact-associations.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
log = get_logger(purpose="create-event-contact-associations")


def process_shard(shard_id, dry_run, id_start=0) -> None:
def process_shard(shard_id, dry_run, id_start: int = 0) -> None:
# At 500K events, we need to process 6 events per second to finish within a day.
batch_size = 100
rps = 6 / batch_size
Expand Down
2 changes: 1 addition & 1 deletion bin/syncback-service.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def main(prod, config, process_num, syncback_id, enable_profiler) -> None:
os.environ.get("SYNCBACK_PROCESSES", 1) # noqa: PLW1508
)

def start():
def start() -> None:
# Start the syncback service, and just hang out forever
syncback = SyncbackService(syncback_id, process_num, total_processes)

Expand Down
15 changes: 10 additions & 5 deletions inbox/actions/backends/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ def _create_email(account, message):
return msg


def _set_flag(crispin_client, account_id, message_id, flag_name, is_add):
def _set_flag(
crispin_client, account_id, message_id, flag_name, is_add
) -> None:
with session_scope(account_id) as db_session:
uids_for_message = uids_by_folder(message_id, db_session)
if not uids_for_message:
Expand Down Expand Up @@ -185,7 +187,7 @@ def remote_save_draft(crispin_client, account_id, message_id) -> None:

def remote_update_draft(
crispin_client, account_id, message_id, old_message_id_header
):
) -> None:
with session_scope(account_id) as db_session:
account = db_session.query(Account).get(account_id)
message = db_session.query(Message).get(message_id)
Expand Down Expand Up @@ -244,8 +246,11 @@ def remote_delete_draft(


def remote_delete_sent(
crispin_client, account_id, message_id_header, delete_multiple=False
):
crispin_client,
account_id,
message_id_header,
delete_multiple: bool = False,
) -> None:
if "sent" not in crispin_client.folder_names():
log.warning(
"Account has no detected sent folder; not deleting message",
Expand All @@ -255,7 +260,7 @@ def remote_delete_sent(
crispin_client.delete_sent_message(message_id_header, delete_multiple)


def remote_save_sent(crispin_client, account_id, message_id):
def remote_save_sent(crispin_client, account_id, message_id) -> None:
with session_scope(account_id) as db_session:
account = db_session.query(Account).get(account_id)
message = db_session.query(Message).get(message_id)
Expand Down
2 changes: 1 addition & 1 deletion inbox/actions/backends/gmail.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def _encode_labels(labels):

def remote_change_labels(
crispin_client, account_id, message_ids, removed_labels, added_labels
):
) -> None:
uids_for_message: dict[str, list[str]] = {}
with session_scope(account_id) as db_session:
for message_id in message_ids:
Expand Down
2 changes: 1 addition & 1 deletion inbox/api/filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,7 @@ def recurring_events( # noqa: ANN201
ends_before,
ends_after,
db_session,
show_cancelled=False,
show_cancelled: bool = False,
):
# Expands individual recurring events into full instances.
# If neither starts_before or ends_before is given, the recurring range
Expand Down
15 changes: 10 additions & 5 deletions inbox/api/kellogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def format_phone_numbers(phone_numbers): # noqa: ANN201


def encode( # noqa: ANN201
obj, namespace_public_id=None, expand=False, is_n1=False
obj, namespace_public_id=None, expand: bool = False, is_n1: bool = False
):
try:
return _encode(obj, namespace_public_id, expand, is_n1=is_n1)
Expand Down Expand Up @@ -103,7 +103,7 @@ def _convert_timezone_to_iana_tz(original_tz):


def _encode( # noqa: D417
obj, namespace_public_id=None, expand=False, is_n1=False
obj, namespace_public_id=None, expand: bool = False, is_n1: bool = False
):
"""
Returns a dictionary representation of a Nylas model object obj, or
Expand Down Expand Up @@ -455,13 +455,18 @@ class APIEncoder:
"""

def __init__(
self, namespace_public_id=None, expand=False, is_n1=False
self,
namespace_public_id=None,
expand: bool = False,
is_n1: bool = False,
) -> None:
self.encoder_class = self._encoder_factory(
namespace_public_id, expand, is_n1=is_n1
)

def _encoder_factory(self, namespace_public_id, expand, is_n1=False):
def _encoder_factory(
self, namespace_public_id, expand, is_n1: bool = False
):
class InternalEncoder(JSONEncoder):
def default(self, obj):
custom_representation = encode(
Expand All @@ -474,7 +479,7 @@ def default(self, obj):

return InternalEncoder

def cereal(self, obj, pretty=False): # noqa: ANN201, D417
def cereal(self, obj, pretty: bool = False): # noqa: ANN201, D417
"""
Returns the JSON string representation of obj.

Expand Down
6 changes: 4 additions & 2 deletions inbox/auth/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ def update_account(self, account, account_data) -> Never:
"""
raise NotImplementedError()

def get_imap_connection(self, account, use_timeout=True): # noqa: ANN201
def get_imap_connection( # noqa: ANN201
self, account, use_timeout: bool = True
):
host, port = account.imap_endpoint
try:
return create_imap_connection(host, port, use_timeout)
Expand All @@ -80,7 +82,7 @@ def authenticate_imap_connection(self, account, conn) -> Never:
raise NotImplementedError()

def get_authenticated_imap_connection( # noqa: ANN201
self, account, use_timeout=True
self, account, use_timeout: bool = True
):
conn = self.get_imap_connection(account, use_timeout=use_timeout)
self.authenticate_imap_connection(account, conn)
Expand Down
4 changes: 3 additions & 1 deletion inbox/auth/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ def auth_is_invalid(exc): # noqa: ANN201
)


def create_imap_connection(host, port, use_timeout=True): # noqa: ANN201
def create_imap_connection( # noqa: ANN201
host, port, use_timeout: bool = True
):
"""
Return a connection to the IMAP server.

Expand Down
6 changes: 3 additions & 3 deletions inbox/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
env = "prod"


def is_live_env():
def is_live_env() -> bool:
return env in ["prod", "staging"]


Expand Down Expand Up @@ -112,7 +112,7 @@ def _update_config_from_env(config, env):
raise


def _update_config_from_env_variables(config):
def _update_config_from_env_variables(config) -> None:
flags = (
os.environ.get("FEATURE_FLAGS", "") or config.get("FEATURE_FLAGS", "")
).split()
Expand All @@ -124,7 +124,7 @@ def _update_config_from_env_variables(config):
config["CALENDAR_POLL_FREQUENCY"] = calendar_poll_frequencey


def _get_process_name(config):
def _get_process_name(config) -> None:
if os.environ.get("PROCESS_NAME") is not None:
config["PROCESS_NAME"] = os.environ.get("PROCESS_NAME")

Expand Down
8 changes: 5 additions & 3 deletions inbox/contacts/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def _get_participants(msg, excluded_emails=None):


# Not really an algorithm, but it seemed reasonable to put this here?
def is_stale(last_updated, lifespan=14): # noqa: ANN201
def is_stale(last_updated, lifespan: int = 14): # noqa: ANN201
"""
last_updated is a datetime.datetime object
lifespan is measured in days
Expand All @@ -70,7 +70,9 @@ def is_stale(last_updated, lifespan=14): # noqa: ANN201
##


def calculate_contact_scores(messages, time_dependent=True): # noqa: ANN201
def calculate_contact_scores( # noqa: ANN201
messages, time_dependent: bool = True
):
now = datetime.datetime.now()
res: defaultdict[str, int] = defaultdict(int)
for message in messages:
Expand Down Expand Up @@ -152,7 +154,7 @@ def get_message_list_weight(message_ids):


# Helper functions for calculating group scores
def _expand_molecule_pool(molecules_dict):
def _expand_molecule_pool(molecules_dict) -> None:
mditems = [(set(g), msgs) for (g, msgs) in molecules_dict.items()]
for i in range(len(mditems)):
g1, m1 = mditems[i]
Expand Down
6 changes: 4 additions & 2 deletions inbox/contacts/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def __init__(self, account_id, namespace_id) -> None:
provider=self.PROVIDER_NAME,
)

def _get_google_client(self, retry_conn_errors=True):
def _get_google_client(self, retry_conn_errors: bool = True):
"""Return the Google API client."""
with session_scope(self.namespace_id) as db_session:
account = db_session.query(GmailAccount).get(self.account_id)
Expand Down Expand Up @@ -128,7 +128,9 @@ def _parse_contact_result(self, google_contact):
raw_data=raw_data,
)

def get_items(self, sync_from_dt=None, max_results=100000): # noqa: ANN201
def get_items( # noqa: ANN201
self, sync_from_dt=None, max_results: int = 100000
):
"""
Fetches and parses fresh contact data.

Expand Down
4 changes: 3 additions & 1 deletion inbox/contacts/icloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ def _x(key): # Ugly parsing helper for ugly formats
raw_data=cardstring,
)

def get_items(self, sync_from_dt=None, max_results=100000): # noqa: ANN201
def get_items( # noqa: ANN201
self, sync_from_dt=None, max_results: int = 100000
):
with session_scope(self.namespace_id) as db_session:
account = db_session.query(GenericAccount).get(self.account_id)
email_address = account.email_address
Expand Down
2 changes: 1 addition & 1 deletion inbox/contacts/remote_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def __init__(
provider_name,
account_id,
namespace_id,
poll_frequency=300,
poll_frequency: int = 300,
) -> None:
bind_context(self, "contactsync", account_id)
self.provider_name = provider_name
Expand Down
6 changes: 3 additions & 3 deletions inbox/contacts/vcard.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ class VCard(defaultdict):
2: some property was deleted
"""

def __init__(self, ddict="") -> None:
def __init__(self, ddict: str = "") -> None:
if ddict == "":
defaultdict.__init__(self, list)
else:
Expand All @@ -250,7 +250,7 @@ def name(self): # noqa: ANN201
return str(self["N"][0][0]) if self["N"] else ""

@name.setter
def name(self, value):
def name(self, value) -> None:
if not self["N"]:
self["N"] = [("", {})]
self["N"][0][0] = value
Expand All @@ -260,7 +260,7 @@ def fname(self): # noqa: ANN201
return str(self["FN"][0][0]) if self["FN"] else ""

@fname.setter
def fname(self, value):
def fname(self, value) -> None:
self["FN"][0] = (value, {})

def alt_keys(self): # noqa: ANN201
Expand Down
16 changes: 9 additions & 7 deletions inbox/crispin.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def connection_pool(account_id, pool_size=None):
_writable_pool_map: dict[int, "CrispinConnectionPool"] = {}


def writable_connection_pool(account_id, pool_size=1):
def writable_connection_pool(account_id, pool_size: int = 1):
"""
Per-account crispin connection pool, with *read-write* connections.

Expand Down Expand Up @@ -242,7 +242,7 @@ def _should_timeout_connection(self):
# constituent SyncbackTasks.
return self.readonly

def _logout(self, client):
def _logout(self, client) -> None:
try:
client.logout()
except Exception:
Expand Down Expand Up @@ -302,7 +302,7 @@ def get(self, *, timeout: "float | None" = None):
self._queue.put(client)
self._sem.release()

def _set_account_info(self):
def _set_account_info(self) -> None:
with session_scope(self.account_id) as db_session:
account = db_session.query(ImapAccount).get(self.account_id)
self.sync_state = account.sync_state
Expand Down Expand Up @@ -349,7 +349,7 @@ def _new_connection(self):
)


def _exc_callback(exc):
def _exc_callback(exc) -> None:
log.info(
"Connection broken with error; retrying with new connection",
exc_info=True,
Expand Down Expand Up @@ -1125,7 +1125,7 @@ def find_by_header(self, header_name, header_value): # noqa: ANN201
return results

def delete_sent_message( # noqa: ANN201
self, message_id_header, delete_multiple=False
self, message_id_header, delete_multiple: bool = False
):
"""
Delete a message in the sent folder, as identified by the Message-Id
Expand Down Expand Up @@ -1179,7 +1179,9 @@ def delete_draft(self, message_id_header): # noqa: ANN201
self._delete_message(message_id_header)
return draft_deleted

def _delete_message(self, message_id_header, delete_multiple=False):
def _delete_message(
self, message_id_header, delete_multiple: bool = False
) -> bool:
"""
Delete a message from the selected folder, using the Message-Id header
to locate it. Does nothing if no matching messages are found, or if
Expand Down Expand Up @@ -1644,7 +1646,7 @@ def delete_draft(self, message_id_header) -> bool:
return True

def delete_sent_message(
self, message_id_header, delete_multiple=False
self, message_id_header, delete_multiple: bool = False
) -> bool:
"""
Delete a message in the sent folder, as identified by the Message-Id
Expand Down
2 changes: 1 addition & 1 deletion inbox/events/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def delete_remote_event(self, calendar_uid, event_uid, **kwargs) -> None:
# -------- logic for push notification subscriptions -------- #

def _get_access_token_for_push_notifications(
self, account, force_refresh=False
self, account, force_refresh: bool = False
):
if not self.webhook_notifications_enabled(account):
raise OAuthError("Account not enabled for push notifications.")
Expand Down
10 changes: 7 additions & 3 deletions inbox/events/ical.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,9 @@ def import_attached_events(
)


def generate_icalendar_invite(event, invite_type="request"): # noqa: ANN201
def generate_icalendar_invite( # noqa: ANN201
event, invite_type: str = "request"
):
# Generates an iCalendar invite from an event.
assert invite_type in ["request", "cancel"]

Expand Down Expand Up @@ -615,7 +617,7 @@ def generate_icalendar_invite(event, invite_type="request"): # noqa: ANN201


def generate_invite_message( # noqa: ANN201
ical_txt, event, account, invite_type="request"
ical_txt, event, account, invite_type: str = "request"
):
assert invite_type in ["request", "update", "cancel"]
html_body = event.description or ""
Expand Down Expand Up @@ -659,7 +661,9 @@ def generate_invite_message( # noqa: ANN201
return msg


def send_invite(ical_txt, event, account, invite_type="request") -> None:
def send_invite(
ical_txt, event, account, invite_type: str = "request"
) -> None:
# We send those transactional emails through a separate domain.
MAILGUN_API_KEY = config.get("NOTIFICATIONS_MAILGUN_API_KEY") # noqa: N806
MAILGUN_DOMAIN = config.get("NOTIFICATIONS_MAILGUN_DOMAIN") # noqa: N806
Expand Down
2 changes: 1 addition & 1 deletion inbox/events/microsoft/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ def parse_msgraph_range_start_and_until(


def convert_msgraph_patterned_recurrence_to_ical_rrule(
event: MsGraphEvent, *, naive=False
event: MsGraphEvent, *, naive: bool = False
) -> str:
"""
Convert Microsoft Graph PatternedRecurrence to iCal RRULE.
Expand Down
Loading