Skip to content

Commit

Permalink
lint using flake8-simplify (#417)
Browse files Browse the repository at this point in the history
* migrate to pre-commit for linting+formatting

* use flake8-simplify for linting
  • Loading branch information
danieleades authored Nov 30, 2021
1 parent 254c107 commit f2094ad
Show file tree
Hide file tree
Showing 32 changed files with 95 additions and 113 deletions.
1 change: 1 addition & 0 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
max-line-length = 120
per-file-ignores =
tests/data/service_github.py: E501
extend-ignore = SIM106
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ repos:
additional_dependencies:
- flake8-bugbear
- pep8-naming
- flake8-simplify

- repo: https://github.com/pycqa/isort
rev: 5.9.3
Expand Down
12 changes: 6 additions & 6 deletions performance/performance_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import tempfile
import time
import webbrowser
from contextlib import suppress
from pathlib import Path

import click
from jinja2 import Template
Expand All @@ -34,7 +36,7 @@ def start(
# Render conf.py
source_tmp_path_conf = os.path.join(source_tmp_path, "conf.template")
source_tmp_path_conf_final = os.path.join(source_tmp_path, "conf.py")
template = Template(open(source_tmp_path_conf).read())
template = Template(Path(source_tmp_path_conf).read_text())
rendered = template.render(
pages=pages,
needs=needs,
Expand All @@ -52,7 +54,7 @@ def start(
# Render index files
source_tmp_path_index = os.path.join(source_tmp_path, "index.template")
source_tmp_path_index_final = os.path.join(source_tmp_path, "index.rst")
template = Template(open(source_tmp_path_index).read())
template = Template(Path(source_tmp_path_index).read_text())
title = "Index"
rendered = template.render(
pages=pages,
Expand All @@ -73,7 +75,7 @@ def start(
for p in range(pages):
source_tmp_path_page = os.path.join(source_tmp_path, "page.template")
source_tmp_path_page_final = os.path.join(source_tmp_path, f"page_{p}.rst")
template = Template(open(source_tmp_path_page).read())
template = Template(Path(source_tmp_path_page).read_text())
title = f"Page {p}"
rendered = template.render(
page=p,
Expand Down Expand Up @@ -151,10 +153,8 @@ def start(
result_time = end_time - start_time

if browser:
try:
with suppress(Exception):
webbrowser.open_new_tab(project_path)
except Exception:
pass

print(f" Duration: {result_time:.2f} seconds")

Expand Down
4 changes: 2 additions & 2 deletions sphinxcontrib/needs/api/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def add_extra_option(app, name):

extra_options = NEEDS_CONFIG.create_or_get("extra_options", dict)

if name in extra_options.keys():
if name in extra_options:
raise NeedsApiConfigWarning("Option {} already registered.".format(name))

NEEDS_CONFIG.add("extra_options", {name: directives.unchanged}, dict, append=True)
Expand Down Expand Up @@ -142,7 +142,7 @@ def add_warning(app, name, function=None, filter_string=None):

warning_check = function or filter_string

if name in warnings_option.keys():
if name in warnings_option:
raise NeedsApiConfigException(f"Warning {name} already registered.")

# warnings_option[name] = warning_check
Expand Down
23 changes: 11 additions & 12 deletions sphinxcontrib/needs/api/need.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,10 @@ def run():

# Handle status
# Check if status is in needs_statuses. If not raise an error.
if env.app.config.needs_statuses:
if status not in [stat["name"] for stat in env.app.config.needs_statuses]:
raise NeedsStatusNotAllowed(
"Status {0} of need id {1} is not allowed " "by config value 'needs_statuses'.".format(status, need_id)
)
if env.app.config.needs_statuses and status not in [stat["name"] for stat in env.app.config.needs_statuses]:
raise NeedsStatusNotAllowed(
"Status {0} of need id {1} is not allowed " "by config value 'needs_statuses'.".format(status, need_id)
)

if tags is None:
tags = []
Expand Down Expand Up @@ -220,7 +219,7 @@ def run():
if not hasattr(env, "needs_all_needs"):
env.needs_all_needs = {}

if need_id in env.needs_all_needs.keys():
if need_id in env.needs_all_needs:
if id:
raise NeedsDuplicatedId(
"A need with ID {} already exists! "
Expand Down Expand Up @@ -300,11 +299,11 @@ def run():

for link_type in env.config.needs_extra_links:
# Check, if specific link-type got some arguments during method call
if link_type["option"] not in list(kwargs.keys()) and link_type["option"] not in needs_global_options.keys():
if link_type["option"] not in kwargs and link_type["option"] not in needs_global_options:
# if not we set no links, but entry in needS_info must be there
links = []
elif link_type["option"] in needs_global_options.keys() and (
link_type["option"] not in list(kwargs.keys()) or len(str(kwargs[link_type["option"]])) == 0
elif link_type["option"] in needs_global_options and (
link_type["option"] not in kwargs or len(str(kwargs[link_type["option"]])) == 0
):
# If it is in global option, value got already set during prior handling of them
links_string = needs_info[link_type["option"]]
Expand All @@ -317,7 +316,7 @@ def run():
needs_info[link_type["option"]] = links
needs_info["{}_back".format(link_type["option"])] = []

if "copy" not in link_type.keys():
if "copy" not in link_type:
link_type["copy"] = False

if link_type["copy"] and link_type["option"] != "links":
Expand Down Expand Up @@ -401,7 +400,7 @@ def del_need(app, id):
:param app: Sphinx application object.
:param id: Sphinx need id.
"""
if id in app.env.needs_all_needs.keys():
if id in app.env.needs_all_needs:
del app.env.needs_all_needs[id]
else:
logger.warning("Given need id {} not exists!".format(id))
Expand Down Expand Up @@ -609,7 +608,7 @@ def _merge_global_options(app, needs_info, global_options):
for key, value in global_options.items():

# If key already exists in needs_info, this global_option got overwritten manually in current need
if key in needs_info.keys() and needs_info[key]:
if key in needs_info and needs_info[key]:
continue

if isinstance(value, tuple):
Expand Down
6 changes: 3 additions & 3 deletions sphinxcontrib/needs/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def __init__(self):
self.configs = {}

def add(self, name, value, option_type=str, append=False, overwrite=False):
if name not in self.configs.keys():
if name not in self.configs:
self.configs[name] = option_type()
elif not isinstance(self.configs[name], option_type):
raise Exception(
Expand All @@ -28,12 +28,12 @@ def add(self, name, value, option_type=str, append=False, overwrite=False):
self.configs[name] += value

def create(self, name, option_type=str, overwrite=False):
if name in self.configs.keys() and not overwrite:
if name in self.configs and not overwrite:
raise Exception(f"option {name} exists.")
self.configs[name] = option_type()

def create_or_get(self, name, option_type=str):
if name not in self.configs.keys():
if name not in self.configs:
self.configs[name] = option_type()
return self.configs.get(name, None)

Expand Down
11 changes: 5 additions & 6 deletions sphinxcontrib/needs/directives/need.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def run(self):
else:
raise Exception("collapse attribute must be true or false")

hide = True if "hide" in self.options.keys() else False
hide = "hide" in self.options

id = self.options.get("id", None)
content = "\n".join(self.content)
Expand Down Expand Up @@ -363,11 +363,10 @@ def create_back_links(env, option):
needs[link_main][option_back].append(key)

# Handling of links to need_parts inside a need
if link_part:
if link_part in needs[link_main]["parts"]:
if option_back not in needs[link_main]["parts"][link_part].keys():
needs[link_main]["parts"][link_part][option_back] = []
needs[link_main]["parts"][link_part][option_back].append(key)
if link_part and link_part in needs[link_main]["parts"]:
if option_back not in needs[link_main]["parts"][link_part].keys():
needs[link_main]["parts"][link_part][option_back] = []
needs[link_main]["parts"][link_part][option_back].append(key)

env.needs_workflow["backlink_creation_{}".format(option)] = True

Expand Down
2 changes: 1 addition & 1 deletion sphinxcontrib/needs/directives/needextract.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def run(self):
"export_id": self.options.get("export_id", ""),
"layout": self.options.get("layout", None),
"style": self.options.get("style", None),
"show_filters": True if self.options.get("show_filters", False) is None else False,
"show_filters": self.options.get("show_filters", False) is None,
}
env.need_all_needextracts[targetid].update(self.collect_filter_attributes())

Expand Down
8 changes: 4 additions & 4 deletions sphinxcontrib/needs/directives/needflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ def process_needflow(app, doctree, fromdocname):
else:
comment = ""

if "style_part" in link_type.keys() and link_type["style_part"]:
if "style_part" in link_type and link_type["style_part"]:
link_style = "[{style}]".format(style=link_type["style_part"])
else:
link_style = "[dotted]"
Expand All @@ -292,7 +292,7 @@ def process_needflow(app, doctree, fromdocname):
else:
comment = ""

if "style" in link_type.keys() and link_type["style"]:
if "style" in link_type and link_type["style"]:
link_style = "[{style}]".format(style=link_type["style"])
else:
link_style = ""
Expand All @@ -303,12 +303,12 @@ def process_needflow(app, doctree, fromdocname):
]:
continue

if "style_start" in link_type.keys() and link_type["style_start"]:
if "style_start" in link_type and link_type["style_start"]:
style_start = link_type["style_start"]
else:
style_start = "-"

if "style_end" in link_type.keys() and link_type["style_end"]:
if "style_end" in link_type and link_type["style_end"]:
style_end = link_type["style_end"]
else:
style_end = "->"
Expand Down
2 changes: 1 addition & 1 deletion sphinxcontrib/needs/directives/needgantt.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def run(self):
else:
timeline = None # Timeline/scale not set later

no_color = "no_color" in self.options.keys()
no_color = "no_color" in self.options

duration_option = self.options.get("duration_option", env.app.config.needs_duration_option)
completion_option = self.options.get("completion_option", env.app.config.needs_completion_option)
Expand Down
4 changes: 2 additions & 2 deletions sphinxcontrib/needs/directives/needimport.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def run(self):
for id in needs_ids:
# Manipulate links in all link types
for extra_link in env.config.needs_extra_links:
if extra_link["option"] in need.keys() and id in need[extra_link["option"]]:
if extra_link["option"] in need and id in need[extra_link["option"]]:
for n, link in enumerate(need[extra_link["option"]]):
if id == link:
need[extra_link["option"]][n] = "".join([id_prefix, id])
Expand All @@ -151,7 +151,7 @@ def run(self):
need["layout"] = self.options.get("layout", getattr(need, "layout", None))
need["style"] = self.options.get("style", getattr(need, "style", None))
need["style"] = self.options.get("style", getattr(need, "style", None))
if "hide" in self.options.keys():
if "hide" in self.options:
need["hide"] = True
else:
need["hide"] = getattr(need, "hide", None)
Expand Down
6 changes: 3 additions & 3 deletions sphinxcontrib/needs/directives/needlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ def run(self):
"docname": env.docname,
"lineno": self.lineno,
"target_node": targetnode,
"show_tags": True if self.options.get("show_tags", False) is None else False,
"show_status": True if self.options.get("show_status", False) is None else False,
"show_filters": True if self.options.get("show_filters", False) is None else False,
"show_tags": self.options.get("show_tags", False) is None,
"show_status": self.options.get("show_status", False) is None,
"show_filters": self.options.get("show_filters", False) is None,
"export_id": self.options.get("export_id", ""),
"env": env,
}
Expand Down
23 changes: 11 additions & 12 deletions sphinxcontrib/needs/directives/needtable.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ def run(self):
"sort": sort,
# As the following options are flags, the content is None, if set.
# If not set, the options.get() method returns False
"show_filters": True if self.options.get("show_filters", False) is None else False,
"show_parts": True if self.options.get("show_parts", False) is None else False,
"show_filters": self.options.get("show_filters", False) is None,
"show_parts": self.options.get("show_parts", False) is None,
"env": env,
}
env.need_all_needtables[targetid].update(self.collect_filter_attributes())
Expand Down Expand Up @@ -223,13 +223,9 @@ def sort(need):
)
elif option == "TITLE":
row += row_col_maker(app, fromdocname, env.needs_all_needs, temp_need, "title", prefix=prefix)
elif option in link_type_list.keys():
elif option in link_type_list:
link_type = link_type_list[option]
if (
option == "INCOMING"
or option == link_type["option"].upper() + "_BACK"
or option == link_type["incoming"].upper()
):
if option in ["INCOMING", link_type["option"].upper() + "_BACK", link_type["incoming"].upper()]:
row += row_col_maker(
app,
fromdocname,
Expand Down Expand Up @@ -279,10 +275,13 @@ def sort(need):
"content",
prefix=app.config.needs_part_prefix,
)
elif option in link_type_list.keys() and (
option == "INCOMING"
or option == link_type_list[option]["option"].upper() + "_BACK"
or option == link_type_list[option]["incoming"].upper()
elif option in link_type_list and (
option
in [
"INCOMING",
link_type_list[option]["option"].upper() + "_BACK",
link_type_list[option]["incoming"].upper(),
]
):
row += row_col_maker(
app,
Expand Down
2 changes: 1 addition & 1 deletion sphinxcontrib/needs/external_needs.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def load_external_needs(app, env, _docname):

# check if external needs already exist
ext_need_id = need_params["id"]
if ext_need_id in env.needs_all_needs.keys():
if ext_need_id in env.needs_all_needs:
# check need_params for more detail
if (
env.needs_all_needs[ext_need_id]["is_external"]
Expand Down
11 changes: 6 additions & 5 deletions sphinxcontrib/needs/filter_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,12 @@ def process_filters(app, all_needs, current_needlist, include_external=True):
if bool(current_needlist["status"] or current_needlist["tags"] or current_needlist["types"]):
for need_info in all_needs_incl_parts:
status_filter_passed = False
if not current_needlist["status"]:
# Filtering for status was not requested
status_filter_passed = True
elif need_info["status"] and need_info["status"] in current_needlist["status"]:
# Match was found
if (
not current_needlist["status"]
or need_info["status"]
and need_info["status"] in current_needlist["status"]
):
# Filtering for status was not requested or match was found
status_filter_passed = True

tags_filter_passed = False
Expand Down
6 changes: 2 additions & 4 deletions sphinxcontrib/needs/functions/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def register_func(need_function, name=None):
else:
func_name = name

if func_name in NEEDS_FUNCTIONS.keys():
if func_name in NEEDS_FUNCTIONS:
# We can not throw an exception here, as using sphinx-needs in different sphinx-projects with the
# same python interpreter session does not clean NEEDS_FUNCTIONS.
# This is mostly the case during tet runs.
Expand Down Expand Up @@ -303,9 +303,7 @@ def _analyze_func_string(func_string, need):
for arg in func_call.args:
if isinstance(arg, ast.Num):
func_args.append(arg.n)
elif isinstance(arg, ast.Str):
func_args.append(arg.s)
elif isinstance(arg, ast.BoolOp):
elif isinstance(arg, (ast.Str, ast.BoolOp)):
func_args.append(arg.s)
elif isinstance(arg, ast.List):
arg_list = []
Expand Down
5 changes: 2 additions & 3 deletions sphinxcontrib/needs/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""
import os
import re
from contextlib import suppress
from urllib.parse import urlparse

import requests
Expand Down Expand Up @@ -749,10 +750,8 @@ def image(self, url, height=None, width=None, align=None, no_link=False, prefix=

# Download only, if file not downloaded yet
if not os.path.exists(file_path):
try:
with suppress(FileExistsError):
os.mkdir(path)
except FileExistsError:
pass
response = requests.get(url)
if response.status_code == 200:
with open(file_path, "wb") as f:
Expand Down
Loading

0 comments on commit f2094ad

Please sign in to comment.