Skip to content

Commit

Permalink
Replace flake8-simplify with ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
dafeda committed Sep 21, 2023
1 parent c4cfa08 commit 93fbfd6
Show file tree
Hide file tree
Showing 21 changed files with 37 additions and 82 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,5 @@ write_to = "src/ert/shared/version.py"
select = [
"I", # isort
"B", # flake-8-bugbear
"SIM", # flake-8-simplify
]
5 changes: 1 addition & 4 deletions src/ert/config/ert_script.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,7 @@ def initializeAndRun(
) -> Any:
arguments = []
for index, arg_value in enumerate(argument_values):
if index < len(argument_types):
arg_type = argument_types[index]
else:
arg_type = str
arg_type = argument_types[index] if index < len(argument_types) else str

if arg_value is not None:
arguments.append(arg_type(arg_value))

Check failure on line 92 in src/ert/config/ert_script.py

View workflow job for this annotation

GitHub Actions / type-checking (3.11)

"object" not callable
Expand Down
5 changes: 1 addition & 4 deletions src/ert/dark_storage/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,7 @@ def data_for_key(
elif key in res.get_gen_data_keys():
key_parts = key.split("@")
key = key_parts[0]
if len(key_parts) > 1:
report_step = int(key_parts[1])
else:
report_step = 0
report_step = int(key_parts[1]) if len(key_parts) > 1 else 0

try:
data = res.load_gen_data(
Expand Down
17 changes: 8 additions & 9 deletions src/ert/ensemble_evaluator/_wait_for_evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,14 @@ async def attempt_connection(
) -> None:
timeout = aiohttp.ClientTimeout(connect=connection_timeout)
headers = {} if token is None else {"token": token}
async with aiohttp.ClientSession() as session:
async with session.request(
method="get",
url=url,
ssl=get_ssl_context(cert),
headers=headers,
timeout=timeout,
) as resp:
resp.raise_for_status()
async with aiohttp.ClientSession() as session, session.request(
method="get",
url=url,
ssl=get_ssl_context(cert),
headers=headers,
timeout=timeout,
) as resp:
resp.raise_for_status()


async def wait_for_evaluator( # pylint: disable=too-many-arguments
Expand Down
5 changes: 1 addition & 4 deletions src/ert/gui/ertwidgets/listeditbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,7 @@ def validateList(self):

validity_type = ValidationSupport.WARNING

if not valid:
color = ValidationSupport.ERROR_COLOR
else:
color = self._valid_color
color = ValidationSupport.ERROR_COLOR if not valid else self._valid_color

self._validation_support.setValidationMessage(message, validity_type)
self._list_edit_line.setToolTip(message)
Expand Down
5 changes: 1 addition & 4 deletions src/ert/gui/ertwidgets/pathchooser.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,7 @@ def validatePath(self):

validity_type = ValidationSupport.WARNING

if not valid:
color = ValidationSupport.ERROR_COLOR
else:
color = self.valid_color
color = ValidationSupport.ERROR_COLOR if not valid else self.valid_color

self._validation_support.setValidationMessage(message, validity_type)
self._path_line.setToolTip(message)
Expand Down
16 changes: 5 additions & 11 deletions src/ert/gui/model/snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,9 @@ def prerender(
snapshot.data()[ids.REALS].keys(), key=int
)
metadata[SORTED_JOB_IDS] = {}
for real_id in snapshot.reals.keys():
for real_id in snapshot.reals:
metadata[SORTED_JOB_IDS][real_id] = {}
for step_id in snapshot.steps(real_id).keys():
for step_id in snapshot.steps(real_id):
indices = [
(job.index, job_id)
for job_id, job in snapshot.jobs(real_id, step_id).items()
Expand All @@ -135,7 +135,7 @@ def prerender(
for step in real[ids.STEPS].values():
if ids.JOBS not in step:
continue
for job_id in step[ids.JOBS].keys():
for job_id in step[ids.JOBS]:
status = step[ids.JOBS][job_id][ids.STATUS]
color = _QCOLORS[state.JOB_STATE_TO_COLOR[status]]
metadata[REAL_JOB_STATUS_AGGREGATED][real_id][job_id] = color
Expand Down Expand Up @@ -327,10 +327,7 @@ def columnCount(self, parent: QModelIndex = None):
def rowCount(self, parent: QModelIndex = None):
if parent is None:
parent = QModelIndex()
if not parent.isValid():
parentItem = self.root
else:
parentItem = parent.internalPointer()
parentItem = self.root if not parent.isValid() else parent.internalPointer()

if parent.column() > 0:
return 0
Expand Down Expand Up @@ -475,10 +472,7 @@ def index(self, row: int, column: int, parent: QModelIndex = None) -> QModelInde
if not self.hasIndex(row, column, parent):
return QModelIndex()

if not parent.isValid():
parent_item = self.root
else:
parent_item = parent.internalPointer()
parent_item = self.root if not parent.isValid() else parent.internalPointer()

child_item = None
try:
Expand Down
5 changes: 1 addition & 4 deletions src/ert/gui/plottery/plots/distribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,7 @@ def _plotDistribution(
index,
previous_data,
):
if data.empty:
data = pd.Series(dtype="float64")
else:
data = data[0]
data = pd.Series(dtype="float64") if data.empty else data[0]

axes.set_xlabel(plot_config.xLabel())
axes.set_ylabel(plot_config.yLabel())
Expand Down
10 changes: 2 additions & 8 deletions src/ert/gui/plottery/plots/histogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,9 @@ def plotHistogram(
else:
current_min = data[case].min()
current_max = data[case].max()
if minimum is None:
minimum = current_min
else:
minimum = min(minimum, current_min)
minimum = current_min if minimum is None else min(minimum, current_min)

if maximum is None:
maximum = current_max
else:
maximum = max(maximum, current_max)
maximum = current_max if maximum is None else max(maximum, current_max)

max_element_count = max(max_element_count, len(data[case].index))

Expand Down
5 changes: 1 addition & 4 deletions src/ert/gui/simulation/view/realization.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,7 @@ def _paint_inner_grid(self, painter: QPainter, rect: QRect, colors) -> None:

for y in range(grid_dim):
for x in range(grid_dim):
if k >= job_nr:
color = QColorConstants.Gray
else:
color = colors[k]
color = QColorConstants.Gray if k >= job_nr else colors[k]
foreground_image.setPixel(x, y, color.rgb())
k += 1
_image_cache[colors_hash] = foreground_image
Expand Down
5 changes: 1 addition & 4 deletions src/ert/gui/tools/manage_cases/case_init_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,7 @@ def _showInfoForCase(self, index=None):
states = []
else:
ensemble = self.show_case_info_case_selector.itemData(index)
if ensemble is not None:
states = ensemble.state_map
else:
states = []
states = ensemble.state_map if ensemble is not None else []

html = "<table>"
for state_index, value in enumerate(states):
Expand Down
5 changes: 1 addition & 4 deletions src/ert/libres_facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,10 +235,7 @@ def observation_keys(self, key: str) -> List[str]:
if key in self.get_gen_data_keys():
key_parts = key.split("@")
data_key = key_parts[0]
if len(key_parts) > 1:
data_report_step = int(key_parts[1])
else:
data_report_step = 0
data_report_step = int(key_parts[1]) if len(key_parts) > 1 else 0

obs_key = None

Expand Down
4 changes: 2 additions & 2 deletions src/ert/shared/feature_toggling.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def is_enabled(feature_name: str) -> bool:

@staticmethod
def add_feature_toggling_args(parser: ArgumentParser) -> None:
for feature_name in FeatureToggling._conf.keys():
for feature_name in FeatureToggling._conf:
parser.add_argument(
f"--{FeatureToggling._get_arg_name(feature_name)}",
action="store_true",
Expand All @@ -49,7 +49,7 @@ def add_feature_toggling_args(parser: ArgumentParser) -> None:
@staticmethod
def update_from_args(args: Namespace) -> None:
args_dict = vars(args)
for feature_name in FeatureToggling._conf.keys():
for feature_name in FeatureToggling._conf:
arg_name = FeatureToggling._get_arg_name(feature_name)
feature_name_escaped = arg_name.replace("-", "_")

Expand Down
4 changes: 2 additions & 2 deletions src/ert/shared/plugins/plugin_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ def get_documentation_for_jobs(self) -> Dict[str, Any]:
self.hook.installable_jobs(), include_plugin_data=True
).items()
}
for k in job_docs.keys():
for k in job_docs:
job_docs[k].update(
ErtPluginManager._evaluate_job_doc_hook(
self.hook.job_documentation,
Expand Down Expand Up @@ -349,7 +349,7 @@ def _setup_temp_environment_if_not_already_set(
)

def _reset_environment(self) -> None:
for name in self.env.keys():
for name in self.env:
if self.backup_env.get(name) is None and name in os.environ:
logging.debug(f"Resetting environment variable {name}")
del os.environ[name]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,7 @@ def _get_env(self, version: str, exe_type: str) -> Dict[str, str]:
def _get_sim(self, version: Optional[str], exe_type: str) -> Simulator:
version = self._get_version(version)
binaries: Dict[str, str] = self._config[Keys.versions][version][exe_type]
if exe_type == Keys.mpi:
mpirun = binaries[Keys.mpirun]
else:
mpirun = None
mpirun = binaries[Keys.mpirun] if exe_type == Keys.mpi else None
return Simulator(
version,
binaries[Keys.executable],
Expand All @@ -160,8 +157,8 @@ def mpi_sim(self, version: Optional[str] = None) -> Simulator:

def simulators(self, strict: bool = True) -> List[Simulator]:
simulators = []
for version in self._config[Keys.versions].keys():
for exe_type in self._config[Keys.versions][version].keys():
for version in self._config[Keys.versions]:
for exe_type in self._config[Keys.versions][version]:
if strict:
sim = self._get_sim(version, exe_type)
else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,7 @@ def _expand_SLURM_task_count(task_count_string):
print(match_dict)
count = int(match_dict["count"])
mult_string = match_dict["mult"]
if mult_string is None:
mult = 1
else:
mult = int(mult_string)
mult = 1 if mult_string is None else int(mult_string)

return [count] * mult
else:
Expand Down
5 changes: 1 addition & 4 deletions src/ert/storage/local_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,7 @@ def create_ensemble(
name: Optional[str] = None,
prior_ensemble: Optional[Union[LocalEnsembleReader, UUID]] = None,
) -> LocalEnsembleAccessor:
if isinstance(experiment, UUID):
experiment_id = experiment
else:
experiment_id = experiment.id
experiment_id = experiment if isinstance(experiment, UUID) else experiment.id

uuid = uuid4()
path = self._ensemble_path(uuid)
Expand Down
2 changes: 1 addition & 1 deletion tests/unit_tests/analysis/test_row_scaling.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def test_row_scaling_factor_0_for_all_parameters():
((A, row_scaling),) = ensemble_smoother_update_step_row_scaling(
S, [(A, row_scaling)], np.full(observations.shape, 0.5), observations
)
assert np.all(A == A_copy)
assert np.all(A_copy == A)


def test_row_scaling_factor_1_for_either_parameter():
Expand Down
2 changes: 1 addition & 1 deletion tests/unit_tests/config/test_forward_model_data_to_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def validate_ext_job(ext_job, ext_job_config):
assert ext_job.environment == ExtJob.default_env
else:
assert ext_job.environment.keys() == ext_job_config["environment"].keys()
for key in ext_job_config["environment"].keys():
for key in ext_job_config["environment"]:
assert ext_job.environment[key] == ext_job_config["environment"][key]


Expand Down
2 changes: 1 addition & 1 deletion tests/unit_tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def log_check():
logger_after = logging.getLogger()
level_after = logger_after.getEffectiveLevel()
assert (
logging.WARNING == level_after
level_after == logging.WARNING
), f"Detected differences in log environment: Changed to {level_after}"


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -324,4 +324,4 @@ def exploding_handler(events):
# drain the monitor
list(monitor.track())

assert ENSEMBLE_STATE_FAILED == evaluator.ensemble.snapshot.status
assert evaluator.ensemble.snapshot.status == ENSEMBLE_STATE_FAILED

0 comments on commit 93fbfd6

Please sign in to comment.