refactor: simplify conditional logic

Command: `sourcery review --fix --enable de-morgan .`
This commit is contained in:
barredterra 2023-12-05 11:14:41 +01:00
parent b45df8d726
commit c35476256f
42 changed files with 61 additions and 54 deletions

View file

@ -150,7 +150,7 @@ class AutoRepeat(Document):
def validate_auto_repeat_days(self):
auto_repeat_days = self.get_auto_repeat_days()
if not len(set(auto_repeat_days)) == len(auto_repeat_days):
if len(set(auto_repeat_days)) != len(auto_repeat_days):
repeated_days = get_repeated(auto_repeat_days)
plural = "s" if len(repeated_days) > 1 else ""

View file

@ -1289,7 +1289,7 @@ def trim_database(context, dry_run, format, no_backup, yes=False):
for table_name in database_tables:
if not table_name.startswith("tab"):
continue
if not (table_name.replace("tab", "", 1) in doctype_tables or table_name in STANDARD_TABLES):
if table_name.replace("tab", "", 1) not in doctype_tables and table_name not in STANDARD_TABLES:
TABLES_TO_DROP.append(table_name)
if not TABLES_TO_DROP:

View file

@ -191,7 +191,8 @@ def _make(
def validate_email(doc: "Communication") -> None:
"""Validate Email Addresses of Recipients and CC"""
if (
not (doc.communication_type == "Communication" and doc.communication_medium == "Email")
doc.communication_type != "Communication"
or doc.communication_medium != "Email"
or doc.flags.in_receive
):
return

View file

@ -179,7 +179,7 @@ class Importer:
log_index += 1
if not self.data_import.status == "Partial Success":
if self.data_import.status != "Partial Success":
self.data_import.db_set("status", "Partial Success")
# commit after every successful import

View file

@ -292,7 +292,7 @@ class DocType(Document):
if not [d.fieldname for d in self.fields if d.in_list_view]:
cnt = 0
for d in self.fields:
if d.reqd and not d.hidden and not d.fieldtype in not_allowed_in_list_view:
if d.reqd and not d.hidden and d.fieldtype not in not_allowed_in_list_view:
d.in_list_view = 1
cnt += 1
if cnt == 4:
@ -307,7 +307,7 @@ class DocType(Document):
def check_indexing_for_dashboard_links(self):
"""Enable indexing for outgoing links used in dashboard"""
for d in self.fields:
if d.fieldtype == "Link" and not (d.unique or d.search_index):
if d.fieldtype == "Link" and not d.unique and not d.search_index:
referred_as_link = frappe.db.exists(
"DocType Link",
{"parent": d.options, "link_doctype": self.name, "link_fieldname": d.fieldname},
@ -414,7 +414,7 @@ class DocType(Document):
if self.has_web_view:
# route field must be present
if not "route" in [d.fieldname for d in self.fields]:
if "route" not in [d.fieldname for d in self.fields]:
frappe.throw(_('Field "route" is mandatory for Web Views'), title="Missing Field")
# clear website cache
@ -1267,7 +1267,7 @@ def validate_fields(meta):
),
WrongOptionsDoctypeLinkError,
)
elif not (options == d.options):
elif options != d.options:
frappe.throw(
_("{0}: Options {1} must be the same as doctype name {2} for the field {3}").format(
docname, d.options, options, d.label
@ -1515,7 +1515,7 @@ def validate_fields(meta):
def check_table_multiselect_option(docfield):
"""check if the doctype provided in Option has atleast 1 Link field"""
if not docfield.fieldtype == "Table MultiSelect":
if docfield.fieldtype != "Table MultiSelect":
return
doctype = docfield.options
@ -1581,7 +1581,7 @@ def validate_fields(meta):
title=_("Invalid Option"),
)
if not (meta.is_virtual == child_doctype_meta.is_virtual):
if meta.is_virtual != child_doctype_meta.is_virtual:
error_msg = " should be virtual." if meta.is_virtual else " cannot be virtual."
frappe.throw(
_("Child Table {0} for field {1}" + error_msg).format(
@ -1893,7 +1893,7 @@ def check_email_append_to(doc):
if doc.sender_field and not sender_field:
frappe.throw(_("Select a valid Sender Field for creating documents from Email"))
if not sender_field.options == "Email":
if sender_field.options != "Email":
frappe.throw(_("Sender Field should have Email in options"))

View file

@ -21,7 +21,7 @@ class DomainSettings(Document):
active_domains = [d.domain for d in self.active_domains]
added = False
for d in domains:
if not d in active_domains:
if d not in active_domains:
self.append("active_domains", dict(domain=d))
added = True

View file

@ -32,7 +32,7 @@ def deduplicate_dynamic_links(doc):
links, duplicate = [], False
for l in doc.links or []:
t = (l.link_doctype, l.link_name)
if not t in links:
if t not in links:
links.append(t)
else:
duplicate = True

View file

@ -47,7 +47,7 @@ class ModuleDef(Document):
if not frappe.local.module_app.get(frappe.scrub(self.name)):
with open(frappe.get_app_path(self.app_name, "modules.txt")) as f:
content = f.read()
if not self.name in content.splitlines():
if self.name not in content.splitlines():
modules = list(filter(None, content.splitlines()))
modules.append(self.name)

View file

@ -87,7 +87,8 @@ class Report(Document):
if (
self.is_standard == "Yes"
and not cint(getattr(frappe.local.conf, "developer_mode", 0))
and not (frappe.flags.in_migrate or frappe.flags.in_patch)
and not frappe.flags.in_migrate
and not frappe.flags.in_patch
):
frappe.throw(_("You are not allowed to delete Standard Report"))
delete_custom_role("report", self.name)

View file

@ -23,7 +23,7 @@ EVENT_MAP = {
def run_server_script_for_doc_event(doc, event):
# run document event method
if not event in EVENT_MAP:
if event not in EVENT_MAP:
return
if frappe.flags.in_install:

View file

@ -281,7 +281,7 @@ class MariaDBDatabase(MariaDBConnectionUtil, MariaDBExceptionUtil, Database):
)
def create_global_search_table(self):
if not "__global_search" in self.get_tables():
if "__global_search" not in self.get_tables():
self.sql(
"""create table __global_search(
doctype varchar(100),

View file

@ -288,7 +288,7 @@ class PostgresDatabase(PostgresExceptionUtil, Database):
)
def create_global_search_table(self):
if not "__global_search" in self.get_tables():
if "__global_search" not in self.get_tables():
self.sql(
"""create table "__global_search"(
doctype varchar(100),

View file

@ -317,7 +317,7 @@ def get_result(data, timegrain, from_date, to_date, chart_type):
d[1] += data[data_index][1]
count += data[data_index][2]
data_index += 1
if chart_type == "Average" and not count == 0:
if chart_type == "Average" and count != 0:
d[1] = d[1] / count
if chart_type == "Count":
d[1] = count

View file

@ -51,7 +51,7 @@ def save_chart_config(reset, config, chart_name):
chart_config[chart_name] = {}
else:
config = frappe.parse_json(config)
if not chart_name in chart_config:
if chart_name not in chart_config:
chart_config[chart_name] = {}
chart_config[chart_name].update(config)

View file

@ -96,7 +96,7 @@ def get_default_listview_fields(doctype):
fields = [f.get("fieldname") for f in doctype_json.get("fields") if f.get("in_list_view")]
if meta.title_field:
if not meta.title_field.strip() in fields:
if meta.title_field.strip() not in fields:
fields.append(meta.title_field.strip())
return fields

View file

@ -87,7 +87,7 @@ class DocTags:
def add(self, dn, tag):
"""add a new user tag"""
tl = self.get_tags(dn).split(",")
if not tag in tl:
if tag not in tl:
tl.append(tag)
if not frappe.db.exists("Tag", tag):
frappe.get_doc({"doctype": "Tag", "name": tag}).insert(ignore_permissions=True)

View file

@ -437,7 +437,7 @@ def get_title_values_for_link_and_dynamic_link_fields(doc, link_fields=None):
doctype = field.options if field.fieldtype == "Link" else doc.get(field.options)
meta = frappe.get_meta(doctype)
if not meta or not (meta.title_field and meta.show_title_field_in_link):
if not meta or not meta.title_field or not meta.show_title_field_in_link:
continue
link_title = frappe.db.get_value(

View file

@ -584,7 +584,7 @@ def get_filter_dashboard_data(stats, doctype, filters=None):
columns = frappe.db.get_table_columns(doctype)
for tag in tags:
if not tag["name"] in columns:
if tag["name"] not in columns:
continue
tagcount = []
if tag["type"] not in ["Date", "Datetime"]:

View file

@ -235,7 +235,7 @@ class AutoEmailReport(Document):
else:
message = self.get_html_table()
if not self.format == "HTML":
if self.format != "HTML":
attachments = [{"fname": self.get_file_name(), "fcontent": data}]
frappe.sendmail(

View file

@ -58,7 +58,7 @@ def _new_site(
print(f"Site {site} already exists")
sys.exit(1)
if no_mariadb_socket and not db_type == "mariadb":
if no_mariadb_socket and db_type != "mariadb":
print("--no-mariadb-socket requires db_type to be set to mariadb.")
sys.exit(1)

View file

@ -90,7 +90,7 @@ class TestSocialLoginKey(FrappeTestCase):
def make_social_login_key(**kwargs):
kwargs["doctype"] = "Social Login Key"
if not "provider_name" in kwargs:
if "provider_name" not in kwargs:
kwargs["provider_name"] = "Test OAuth2 Provider"
return frappe.get_doc(kwargs)

View file

@ -850,7 +850,7 @@ class BaseDocument:
return
for df in self.meta.get_select_fields():
if df.fieldname == "naming_series" or not (self.get(df.fieldname) and df.options):
if df.fieldname == "naming_series" or not self.get(df.fieldname) or not df.options:
continue
options = (df.options or "").split("\n")

View file

@ -67,7 +67,7 @@ def set_user_and_static_default_values(doc):
)
if user_default_value is not None:
# if fieldtype is link check if doc exists
if not df.fieldtype == "Link" or frappe.db.exists(df.options, user_default_value):
if df.fieldtype != "Link" or frappe.db.exists(df.options, user_default_value):
doc.set(df.fieldname, user_default_value)
else:

View file

@ -465,7 +465,7 @@ class DatabaseQuery:
# add tables from fields
if self.fields:
for field in self.fields:
if not ("tab" in field and "." in field) or any(x for x in sql_functions if x in field):
if "tab" not in field or "." not in field or any(x for x in sql_functions if x in field):
continue
table_name = field.split(".", 1)[0]
@ -478,7 +478,7 @@ class DatabaseQuery:
if table_name.lower().startswith("group_concat("):
table_name = table_name[13:]
if not table_name[0] == "`":
if table_name[0] != "`":
table_name = f"`{table_name}`"
if (
table_name not in self.query_tables and table_name not in self.linked_table_aliases.values()
@ -927,7 +927,8 @@ class DatabaseQuery:
role_permissions = frappe.permissions.get_role_permissions(self.doctype_meta, user=self.user)
if (
not self.doctype_meta.istable
and not (role_permissions.get("select") or role_permissions.get("read"))
and not role_permissions.get("select")
and not role_permissions.get("read")
and not self.flags.ignore_permissions
and not has_any_user_permission_for_doctype(self.doctype, self.user, self.reference_doctype)
):

View file

@ -620,7 +620,7 @@ class Document(BaseDocument):
workflow = self.meta.get_workflow()
if workflow:
validate_workflow(self)
if not self._action == "save":
if self._action != "save":
set_workflow_state_on_action(self, workflow, self._action)
def validate_set_only_once(self):

View file

@ -384,7 +384,7 @@ def validate_rename(
):
frappe.throw(_("You need write permission to rename"))
if not (force or ignore_permissions) and not meta.allow_rename:
if not force and not ignore_permissions and not meta.allow_rename:
frappe.throw(_("{0} not allowed to be renamed").format(_(doctype)))
# validate naming like it's done in doc.py

View file

@ -405,7 +405,7 @@ def get_valid_perms(doctype=None, user=None):
doctypes_with_custom_perms = get_doctypes_with_custom_docperms()
for p in perms:
if not p.parent in doctypes_with_custom_perms:
if p.parent not in doctypes_with_custom_perms:
custom_perms.append(p)
if doctype:

View file

@ -66,7 +66,8 @@ class PrintFormat(Document):
if (
self.standard == "Yes"
and not frappe.local.conf.get("developer_mode")
and not (frappe.flags.in_migrate or frappe.flags.in_test)
and not frappe.flags.in_migrate
and not frappe.flags.in_test
):
frappe.throw(frappe._("Standard Print Format cannot be updated"))

View file

@ -23,7 +23,7 @@ class PrintFormatFieldTemplate(Document):
template_file: DF.Data | None
# end: auto-generated types
def validate(self):
if self.standard and not (frappe.conf.developer_mode or frappe.flags.in_patch):
if self.standard and not frappe.conf.developer_mode and not frappe.flags.in_patch:
frappe.throw(_("Enable developer mode to create a standard Print Template"))
def before_insert(self):

View file

@ -24,7 +24,8 @@ class PrintStyle(Document):
if (
self.standard == 1
and not frappe.local.conf.get("developer_mode")
and not (frappe.flags.in_import or frappe.flags.in_test)
and not frappe.flags.in_import
and not frappe.flags.in_test
):
frappe.throw(frappe._("Standard Print Style cannot be changed. Please duplicate to edit."))

View file

@ -7,7 +7,7 @@ UI_TEST_USER = "frappe@example.com"
def whitelist_for_tests(fn):
if frappe.request and not (frappe.flags.in_test or getattr(frappe.local, "dev_server", 0)):
if frappe.request and not frappe.flags.in_test and not getattr(frappe.local, "dev_server", 0):
frappe.throw("Cannot run UI tests. Use a development server with `bench start`")
return frappe.whitelist()(fn)

View file

@ -350,7 +350,7 @@ def get_messages_from_doctype(name):
if d.fieldtype == "Select" and d.options:
options = d.options.split("\n")
if not "icon" in options[0]:
if "icon" not in options[0]:
messages.extend(options)
if d.fieldtype == "HTML" and d.options:
messages.append(d.options)

View file

@ -136,7 +136,7 @@ class BackupGenerator:
self.backup_includes = passed_tables["include"]
self.backup_excludes = passed_tables["exclude"]
if not (self.backup_includes or self.backup_excludes) and not self.ignore_conf:
if not self.backup_includes and not self.backup_excludes and not self.ignore_conf:
self.backup_includes = self.backup_includes or conf_tables["include"]
self.backup_excludes = self.backup_excludes or conf_tables["exclude"]

View file

@ -1596,7 +1596,7 @@ def get_url(uri: str | None = None, full_address: bool = False) -> str:
if not host_name:
host_name = "http://127.0.0.1"
if host_name and not (host_name.startswith("http://") or host_name.startswith("https://")):
if host_name and not host_name.startswith("http://") and not host_name.startswith("https://"):
host_name = "http://" + host_name
if not uri and full_address:
@ -1605,7 +1605,8 @@ def get_url(uri: str | None = None, full_address: bool = False) -> str:
port = frappe.conf.http_port or frappe.conf.webserver_port
if (
not (frappe.conf.restart_supervisor_on_update or frappe.conf.restart_systemd_on_update)
not frappe.conf.restart_supervisor_on_update
and not frappe.conf.restart_systemd_on_update
and host_name
and not url_contains_port(host_name)
and port

View file

@ -145,7 +145,7 @@ def get_admin_password():
def ask_admin_password():
admin_password = getpass.getpass("Set Administrator password: ")
admin_password2 = getpass.getpass("Re-enter Administrator password: ")
if not admin_password == admin_password2:
if admin_password != admin_password2:
print("\nPasswords do not match")
return ask_admin_password()
return admin_password

View file

@ -125,7 +125,7 @@ class WebPage(WebsiteGenerator):
frappe.flags.web_block_styles = {}
try:
context["main_section"] = render_template(context.main_section, context)
if not "<!-- static -->" in context.main_section:
if "<!-- static -->" not in context.main_section:
context["no_cache"] = 1
except TemplateSyntaxError:
raise
@ -137,13 +137,13 @@ class WebPage(WebsiteGenerator):
"""Build breadcrumbs template"""
if self.breadcrumbs:
context.parents = frappe.safe_eval(self.breadcrumbs, {"_": _})
if not "no_breadcrumbs" in context:
if "no_breadcrumbs" not in context:
if "<!-- no-breadcrumbs -->" in context.main_section:
context.no_breadcrumbs = 1
def set_title_and_header(self, context):
"""Extract and set title and header from content or context."""
if not "no_header" in context:
if "no_header" not in context:
if "<!-- no-header -->" in context.main_section:
context.no_header = 1

View file

@ -28,7 +28,7 @@ class WebTemplate(Document):
type: DF.Literal["Component", "Section", "Navbar", "Footer"]
# end: auto-generated types
def validate(self):
if self.standard and not (frappe.conf.developer_mode or frappe.flags.in_patch):
if self.standard and not frappe.conf.developer_mode and not frappe.flags.in_patch:
frappe.throw(_("Enable developer mode to create a standard Web Template"))
for field in self.fields:

View file

@ -53,7 +53,8 @@ class WebsiteTheme(Document):
if (
not self.custom
and frappe.local.conf.get("developer_mode")
and not (frappe.flags.in_import or frappe.flags.in_test)
and not frappe.flags.in_import
and not frappe.flags.in_test
):
self.export_doc()

View file

@ -109,12 +109,12 @@ def get_pages_from_path(start, app, app_path):
if os.path.exists(start_path):
for basepath, folders, files in os.walk(start_path):
# add missing __init__.py
if not "__init__.py" in files and frappe.conf.get("developer_mode"):
if "__init__.py" not in files and frappe.conf.get("developer_mode"):
open(os.path.join(basepath, "__init__.py"), "a").close()
for fname in files:
fname = frappe.utils.cstr(fname)
if not "." in fname:
if "." not in fname:
continue
page_name, extn = fname.rsplit(".", 1)
if extn in ("js", "css") and os.path.exists(os.path.join(basepath, page_name + ".html")):

View file

@ -104,7 +104,7 @@ class Workflow(Document):
for key in new_states:
if key in before_save_states:
if not new_states[key].doc_status == before_save_states[key].doc_status:
if new_states[key].doc_status != before_save_states[key].doc_status:
frappe.db.set_value(
self.document_type,
{self.workflow_state_field: before_save_states[key].state},

View file

@ -244,7 +244,7 @@ def set_title_values_for_link_and_dynamic_link_fields(meta, doc, parent_doc=None
doctype = field.options if field.fieldtype == "Link" else doc.get(field.options)
meta = frappe.get_meta(doctype)
if not meta or not (meta.title_field and meta.show_title_field_in_link):
if not meta or not meta.title_field or not meta.show_title_field_in_link:
continue
link_title = frappe.get_cached_value(doctype, doc.get(field.fieldname), meta.title_field)

View file

@ -18,7 +18,7 @@ def get_query_key():
query_string = frappe.local.request.query_string
query = dict(parse_qsl(query_string))
query = {key.decode(): val.decode() for key, val in query.items()}
if not "k" in list(query):
if "k" not in list(query):
frappe.throw(_("Not Permitted"), frappe.PermissionError)
query = (query["k"]).strip()
if False in [i.isalpha() or i.isdigit() for i in query]: