ruff: Fix PLR1714 Consider merging multiple comparisons.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2023-07-21 16:15:10 -07:00 committed by Tim Abbott
parent 3b09197fdf
commit 2ae285af7c
19 changed files with 42 additions and 57 deletions

View File

@ -60,7 +60,7 @@ def raw_user_activity_table(records: QuerySet[UserActivity]) -> str:
def user_activity_summary_table(user_summary: Dict[str, Dict[str, Any]]) -> str:
rows = []
for k, v in user_summary.items():
if k == "name" or k == "user_profile_id":
if k in ("name", "user_profile_id"):
continue
client = k
count = v["count"]

View File

@ -101,7 +101,7 @@ if not args.noop and not args.force:
sys.stdout.write("Apply changes? [y/N] ")
sys.stdout.flush()
do_apply = sys.stdin.readline().strip().lower()
if do_apply == "" or do_apply == "n":
if do_apply in ("", "n"):
sys.exit(0)
if args.noop and args.force:
@ -115,5 +115,5 @@ ret = subprocess.call([*puppet_cmd, "--detailed-exitcodes"], env=puppet_env)
# ret = 2 => changes, no errors
# ret = 4 => no changes, yes errors
# ret = 6 => changes, yes errors
if ret != 0 and ret != 2:
if ret not in (0, 2):
sys.exit(2)

View File

@ -14,7 +14,7 @@ def check_venv(filename: str) -> None:
"to enter the development environment."
)
if user_name != "vagrant" and user_name != "zulipdev":
if user_name not in ("vagrant", "zulipdev"):
print()
print("If you are using Vagrant, first run `vagrant ssh` to enter the Vagrant guest.")
sys.exit(1)

View File

@ -328,7 +328,7 @@ def main() -> None:
if suite.startswith("test"):
for root, dirs, files_names in os.walk(zerver_test_dir):
for file_name in files_names:
if file_name == suite or file_name == suite + ".py":
if file_name in (suite, f"{suite}.py"):
new_suite = os.path.join(root, file_name)
args[i] = new_suite
break

View File

@ -98,9 +98,9 @@ def set_realm_permissions_based_on_org_type(realm: Realm) -> None:
# Custom configuration for educational organizations. The present
# defaults are designed for a single class, not a department or
# larger institution, since those are more common.
if (
realm.org_type == Realm.ORG_TYPES["education_nonprofit"]["id"]
or realm.org_type == Realm.ORG_TYPES["education"]["id"]
if realm.org_type in (
Realm.ORG_TYPES["education_nonprofit"]["id"],
Realm.ORG_TYPES["education"]["id"],
):
# Limit user creation to administrators.
realm.invite_to_realm_policy = Realm.POLICY_ADMINS_ONLY
@ -216,9 +216,9 @@ def do_create_realm(
)
realm_default_email_address_visibility = RealmUserDefault.EMAIL_ADDRESS_VISIBILITY_EVERYONE
if (
realm.org_type == Realm.ORG_TYPES["education_nonprofit"]["id"]
or realm.org_type == Realm.ORG_TYPES["education"]["id"]
if realm.org_type in (
Realm.ORG_TYPES["education_nonprofit"]["id"],
Realm.ORG_TYPES["education"]["id"],
):
# Email address of users should be initially visible to admins only.
realm_default_email_address_visibility = (

View File

@ -61,9 +61,9 @@ def try_add_realm_custom_profile_field(
display_in_profile_summary=display_in_profile_summary,
)
custom_profile_field.hint = hint
if (
custom_profile_field.field_type == CustomProfileField.SELECT
or custom_profile_field.field_type == CustomProfileField.EXTERNAL_ACCOUNT
if custom_profile_field.field_type in (
CustomProfileField.SELECT,
CustomProfileField.EXTERNAL_ACCOUNT,
):
custom_profile_field.field_data = orjson.dumps(field_data or {}).decode()
@ -109,10 +109,7 @@ def try_update_realm_custom_profile_field(
field.name = name
field.hint = hint
field.display_in_profile_summary = display_in_profile_summary
if (
field.field_type == CustomProfileField.SELECT
or field.field_type == CustomProfileField.EXTERNAL_ACCOUNT
):
if field.field_type in (CustomProfileField.SELECT, CustomProfileField.EXTERNAL_ACCOUNT):
if field.field_type == CustomProfileField.SELECT:
assert field_data is not None
remove_custom_profile_field_value_if_required(field, field_data)

View File

@ -147,7 +147,7 @@ def find_log_origin(record: logging.LogRecord) -> str:
if settings.LOGGING_SHOW_MODULE:
module_name = find_log_caller_module(record)
if module_name == logger_name or module_name == record.name:
if module_name in (logger_name, record.name):
# Abbreviate a bit.
pass
else:

View File

@ -41,12 +41,10 @@ def create_if_missing_realm_internal_bots() -> None:
def send_initial_direct_message(user: UserProfile) -> None:
# We adjust the initial Welcome Bot direct message for education organizations.
education_organization = False
if (
user.realm.org_type == Realm.ORG_TYPES["education_nonprofit"]["id"]
or user.realm.org_type == Realm.ORG_TYPES["education"]["id"]
):
education_organization = True
education_organization = user.realm.org_type in (
Realm.ORG_TYPES["education_nonprofit"]["id"],
Realm.ORG_TYPES["education"]["id"],
)
# We need to override the language in this code path, because it's
# called from account registration, which is a pre-account API

View File

@ -116,7 +116,7 @@ def do_bulk_backfill_extra_data(
)
continue
new_value = ast.literal_eval(audit_log_entry.extra_data) # type: ignore[attr-defined] # Explained above.
if old_value != {} and old_value != new_value:
if old_value not in ({}, new_value):
inconsistent_extra_data_json.append((audit_log_entry.id, audit_log_entry.extra_data, old_value, new_value)) # type: ignore[attr-defined] # Explained above.
audit_log_entry.extra_data_json = new_value # type: ignore[attr-defined] # Explained above.
audit_log_model.objects.bulk_update(python_valued_audit_log_entries, fields=["extra_data_json"])

View File

@ -2011,10 +2011,7 @@ class UserProfile(AbstractBaseUser, PermissionsMixin, UserBaseSettings): # type
@property
def is_realm_admin(self) -> bool:
return (
self.role == UserProfile.ROLE_REALM_ADMINISTRATOR
or self.role == UserProfile.ROLE_REALM_OWNER
)
return self.role in (UserProfile.ROLE_REALM_ADMINISTRATOR, UserProfile.ROLE_REALM_OWNER)
@is_realm_admin.setter
def is_realm_admin(self, value: bool) -> None:

View File

@ -80,7 +80,7 @@ def validate_display_in_profile_summary_field(
# The LONG_TEXT field type doesn't make sense visually for profile
# field summaries. The USER field type will require some further
# client support.
if field_type == CustomProfileField.LONG_TEXT or field_type == CustomProfileField.USER:
if field_type in (CustomProfileField.LONG_TEXT, CustomProfileField.USER):
raise JsonableError(_("Field type not supported for display in profile summary."))

View File

@ -400,7 +400,7 @@ def get_story_create_github_entity_body(payload: WildValue, action: WildValue, e
app_url=action["app_url"].tame(check_string),
),
"name": pull_request_action["number"].tame(check_int)
if entity == "pull-request" or entity == "pull-request-comment"
if entity in ("pull-request", "pull-request-comment")
else pull_request_action["name"].tame(check_string),
"url": pull_request_action["url"].tame(check_string),
"workflow_state_template": "",

View File

@ -77,7 +77,7 @@ def get_opened_or_update_pull_request_body(helper: Helper) -> str:
description = pull_request["body"].tame(check_none_or(check_string))
target_branch = None
base_branch = None
if action == "opened" or action == "merged":
if action in ("opened", "merged"):
target_branch = pull_request["head"]["label"].tame(check_string)
base_branch = pull_request["base"]["label"].tame(check_string)

View File

@ -450,7 +450,7 @@ def get_body_based_on_event(event: str) -> EventFunction:
def get_topic_based_on_event(event: str, payload: WildValue, use_merge_request_title: bool) -> str:
if event == "Push Hook":
return f"{get_repo_name(payload)} / {get_branch_name(payload)}"
elif event == "Job Hook" or event == "Build Hook":
elif event in ("Job Hook", "Build Hook"):
return "{} / {}".format(
payload["repository"]["name"].tame(check_string), get_branch_name(payload)
)
@ -475,7 +475,7 @@ def get_topic_based_on_event(event: str, payload: WildValue, use_merge_request_t
id=payload["object_attributes"]["iid"].tame(check_int),
title=payload["object_attributes"]["title"].tame(check_string),
)
elif event == "Note Hook Issue" or event == "Confidential Note Hook Issue":
elif event in ("Note Hook Issue", "Confidential Note Hook Issue"):
return TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
repo=get_repo_name(payload),
type="issue",

View File

@ -213,15 +213,12 @@ def send_formatted_pagerduty(
"incident.unacknowledged",
):
template = INCIDENT_WITH_SERVICE_AND_ASSIGNEE
elif (
message_type == "incident.resolve" or message_type == "incident.resolved"
) and format_dict.get("agent_info") is not None:
elif message_type in ("incident.resolve", "incident.resolved"):
if "agent_info" in format_dict:
template = INCIDENT_RESOLVED_WITH_AGENT
elif (
message_type == "incident.resolve" or message_type == "incident.resolved"
) and format_dict.get("agent_info") is None:
else:
template = INCIDENT_RESOLVED
elif message_type == "incident.assign" or message_type == "incident.reassigned":
elif message_type in ("incident.assign", "incident.reassigned"):
template = INCIDENT_ASSIGNED
else:
template = INCIDENT_WITH_ASSIGNEE

View File

@ -227,7 +227,7 @@ def compose_notification_message(payload: WildValue) -> str:
# We now split this main function again into two functions. One is for
# "NewErrorOccurred" and "ErrorReoccurred", and one is for the rest. Both
# functions will return a text message that is formatted for the chat.
if event_type == "NewErrorOccurred" or event_type == "ErrorReoccurred":
if event_type in ("NewErrorOccurred", "ErrorReoccurred"):
return notification_message_error_occurred(payload)
elif "FollowUp" in event_type:
return notification_message_follow_up(payload)
@ -285,11 +285,7 @@ def compose_activity_message(payload: WildValue) -> str:
# But, they all are almost identical and the only differences between them
# are the keys at line 9 (check fixtures). So there's no need to split
# the function like the notification one.
if (
event_type == "StatusChanged"
or event_type == "AssignedToUser"
or event_type == "CommentAdded"
):
if event_type in ("StatusChanged", "AssignedToUser", "CommentAdded"):
return activity_message(payload)
else:
raise UnsupportedWebhookEventTypeError(event_type)

View File

@ -56,14 +56,14 @@ def api_sonarr_webhook(
def get_topic_for_http_request(payload: WildValue) -> str:
event_type = payload["eventType"].tame(check_string)
if event_type != "Test" and event_type != "Health":
topic = SONARR_TOPIC_TEMPLATE.format(
series_title=payload["series"]["title"].tame(check_string)
)
elif event_type == "Test":
if event_type == "Test":
topic = SONARR_TOPIC_TEMPLATE_TEST
elif event_type == "Health":
topic = SONARR_TOPIC_TEMPLATE_HEALTH_CHECK.format(level=payload["level"].tame(check_string))
else:
topic = SONARR_TOPIC_TEMPLATE.format(
series_title=payload["series"]["title"].tame(check_string)
)
return topic

View File

@ -43,7 +43,7 @@ def api_wordpress_webhook(
# remove trailing whitespace (issue for some test fixtures)
hook = hook.rstrip()
if hook == "publish_post" or hook == "publish_page":
if hook in ("publish_post", "publish_page"):
data = PUBLISH_POST_OR_PAGE_TEMPLATE.format(type=post_type, title=post_title, url=post_url)
elif hook == "user_register":

View File

@ -71,7 +71,7 @@ def do_bulk_backfill_extra_data(
# are converted back with ast.literal_eval for safety and efficiency.
old_value = audit_log_entry.extra_data_json # type: ignore[attr-defined] # The migration cannot depend on zerver.models, which contains the real type of the RealmAuditLog model, so it cannot be properly typed.
new_value = ast.literal_eval(audit_log_entry.extra_data) # type: ignore[attr-defined] # Explained above.
if old_value != {} and old_value != new_value:
if old_value not in ({}, new_value):
inconsistent_extra_data_json.append((audit_log_entry.id, audit_log_entry.extra_data, old_value, new_value)) # type: ignore[attr-defined] # Explained above.
audit_log_entry.extra_data_json = new_value # type: ignore[attr-defined] # Explained above.
audit_log_model.objects.bulk_update(python_valued_audit_log_entries, fields=["extra_data_json"])