Skip to content

Commit

Permalink
Solve ruff literal-membership
Browse files Browse the repository at this point in the history
ruff check --fix --unsafe-fixes
  • Loading branch information
berland committed Dec 18, 2024
1 parent 7f72c05 commit 6ce4714
Show file tree
Hide file tree
Showing 39 changed files with 79 additions and 84 deletions.
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,6 @@ ignore = [
"PLR0912", # too-many-branches
"PLR0911", # too-many-return-statements
"PLC2701", # import-private-name
"PLR6201", # literal-membership
"PLR0914", # too-many-locals
"PLR6301", # no-self-use
"PLW1641", # eq-without-hash
Expand Down
8 changes: 4 additions & 4 deletions src/ert/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,22 +54,22 @@ def run_cli(args: Namespace, plugin_manager: ErtPluginManager | None = None) ->
f"Config contains forward model step {fm_step_name} {count} time(s)",
)

if not ert_config.observations and args.mode not in [
if not ert_config.observations and args.mode not in {
ENSEMBLE_EXPERIMENT_MODE,
TEST_RUN_MODE,
WORKFLOW_MODE,
]:
}:
raise ErtCliError(
f"To run {args.mode}, observations are needed. \n"
f"Please add an observation file to {args.config}. Example: \n"
f"'OBS_CONFIG observation_file.txt'."
)

if args.mode in [
if args.mode in {
ENSEMBLE_SMOOTHER_MODE,
ES_MDA_MODE,
ITERATIVE_ENSEMBLE_SMOOTHER_MODE,
]:
}:
if not ert_config.ensemble_config.parameter_configs:
raise ErtCliError(
f"To run {args.mode}, GEN_KW, FIELD or SURFACE parameters are needed. \n"
Expand Down
2 changes: 1 addition & 1 deletion src/ert/config/_read_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def _read_spec(
kw = entry.read_keyword()
if kw in arrays:
arrays[kw] = _check_vals(kw, spec, entry.read_array())
if kw in ("WGNAMES ", "NAMES "):
if kw in {"WGNAMES ", "NAMES "}:
wgnames = _check_vals(kw, spec, entry.read_array())
if kw == "DIMENS ":
vals = _check_vals(kw, spec, entry.read_array())
Expand Down
2 changes: 1 addition & 1 deletion src/ert/config/analysis_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def from_dict(cls, config_dict: ConfigDict) -> AnalysisConfig:
)
)
continue
if var_name in ["INVERSION", "IES_INVERSION"]:
if var_name in {"INVERSION", "IES_INVERSION"}:
if value in inversion_str_map[module_name]:
new_value = inversion_str_map[module_name][value]
if var_name == "IES_INVERSION":
Expand Down
4 changes: 2 additions & 2 deletions src/ert/config/gen_kw_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def _check_non_negative_parameter(param: str, prior: PriorDict) -> None:
if prior["function"] == "LOGNORMAL":
_check_non_negative_parameter("MEAN", prior)
_check_non_negative_parameter("STD", prior)
elif prior["function"] in ["NORMAL", "TRUNCATED_NORMAL"]:
elif prior["function"] in {"NORMAL", "TRUNCATED_NORMAL"}:
_check_non_negative_parameter("STD", prior)
if errors:
raise ConfigValidationError.from_collected(errors)
Expand Down Expand Up @@ -494,7 +494,7 @@ class TransformFunction:
use_log: bool = False

def __post_init__(self) -> None:
if self.transform_function_name in ["LOGNORMAL", "LOGUNIF"]:
if self.transform_function_name in {"LOGNORMAL", "LOGUNIF"}:
self.use_log = True

@staticmethod
Expand Down
2 changes: 1 addition & 1 deletion src/ert/config/parsing/config_schema_deprecations.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"dimension set using ENKF_NCOMP keyword. "
"This can be safely removed.",
),
check=lambda line: str(line[1]) in ["ENKF_FORCE_NCOMP"],
check=lambda line: str(line[1]) in {"ENKF_FORCE_NCOMP"},
),
DeprecationInfo(
keyword="RUNPATH",
Expand Down
10 changes: 5 additions & 5 deletions src/ert/config/parsing/observations_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,9 +325,9 @@ def _validate_summary_values(
for key, value in inp.items():
if key == "RESTART":
date_dict.restart = validate_positive_int(value, key)
elif key in ["ERROR", "ERROR_MIN"]:
elif key in {"ERROR", "ERROR_MIN"}:
float_values[str(key)] = validate_positive_float(value, key)
elif key in ["DAYS", "HOURS"]:
elif key in {"DAYS", "HOURS"}:
setattr(date_dict, str(key).lower(), validate_positive_float(value, key))
elif key == "VALUE":
float_values[str(key)] = validate_float(value, key)
Expand Down Expand Up @@ -405,11 +405,11 @@ def _validate_gen_obs_values(
output.restart = validate_positive_int(value, key)
elif key == "VALUE":
output.value = validate_float(value, key)
elif key in ["ERROR", "DAYS", "HOURS"]:
elif key in {"ERROR", "DAYS", "HOURS"}:
setattr(output, str(key).lower(), validate_positive_float(value, key))
elif key in ["DATE", "INDEX_LIST"]:
elif key in {"DATE", "INDEX_LIST"}:
setattr(output, str(key).lower(), value)
elif key in ["OBS_FILE", "INDEX_FILE"]:
elif key in {"OBS_FILE", "INDEX_FILE"}:
filename = value
if not os.path.isabs(filename):
filename = os.path.join(directory, filename)
Expand Down
4 changes: 2 additions & 2 deletions src/ert/config/queue_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ def _group_queue_options_by_queue_system(
grouped[system] = {
option_line[1]: option_line[2]
for option_line in queue_config_list
if option_line[0] in (QueueSystemWithGeneric.GENERIC, system)
if option_line[0] in {QueueSystemWithGeneric.GENERIC, system}
# Empty option values are ignored, yields defaults:
and len(option_line) > 2
}
Expand Down Expand Up @@ -317,7 +317,7 @@ def from_dict(cls, config_dict: ConfigDict) -> QueueConfig:
tags = {
fm_name.lower()
for fm_name, *_ in config_dict.get(ConfigKeys.FORWARD_MODEL, [])
if fm_name in ["RMS", "FLOW", "ECLIPSE100", "ECLIPSE300"]
if fm_name in {"RMS", "FLOW", "ECLIPSE100", "ECLIPSE300"}
}
if tags:
queue_options.project_code = "+".join(tags)
Expand Down
4 changes: 2 additions & 2 deletions src/ert/ensemble_evaluator/_ensemble.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ def _handle_started(self) -> None:
self._state = ENSEMBLE_STATE_STARTED

def _handle_failed(self) -> None:
if self._state not in [
if self._state not in {
ENSEMBLE_STATE_UNKNOWN,
ENSEMBLE_STATE_STARTED,
]:
}:
logger.warning(self._msg, self._state, ENSEMBLE_STATE_FAILED)
self._state = ENSEMBLE_STATE_FAILED

Expand Down
6 changes: 3 additions & 3 deletions src/ert/ensemble_evaluator/evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,10 @@ async def _cancelled_handler(self, events: Sequence[EnsembleCancelled]) -> None:
self.stop()

async def _failed_handler(self, events: Sequence[EnsembleFailed]) -> None:
if self.ensemble.status in (
if self.ensemble.status in {
ENSEMBLE_STATE_STOPPED,
ENSEMBLE_STATE_CANCELLED,
):
}:
return
# if list is empty this call is not triggered by an
# event, but as a consequence of some bad state
Expand Down Expand Up @@ -263,7 +263,7 @@ async def handle_dispatch(self, websocket: ServerConnection) -> None:
)
return

if type(event) in [EnsembleSucceeded, EnsembleFailed]:
if type(event) in {EnsembleSucceeded, EnsembleFailed}:
return
except ConnectionClosedError as connection_error:
# Dispatchers may close the connection abruptly in the case of
Expand Down
4 changes: 2 additions & 2 deletions src/ert/gui/model/fm_step_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,9 @@ def headerData(
if role == Qt.ItemDataRole.DisplayRole:
if orientation == Qt.Orientation.Horizontal:
header = FM_STEP_COLUMNS[section]
if header in [ids.STDOUT, ids.STDERR]:
if header in {ids.STDOUT, ids.STDERR}:
return header.upper()
elif header in [ids.MAX_MEMORY_USAGE]:
elif header in {ids.MAX_MEMORY_USAGE}:
header = header.replace("_", " ")
return header.capitalize()
if orientation == Qt.Orientation.Vertical:
Expand Down
20 changes: 10 additions & 10 deletions src/ert/gui/model/snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,11 +336,11 @@ def data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole) -> A
if index.column() == 1:
return f"{node.data.status}"

if role in (
if role in {
Qt.ItemDataRole.StatusTipRole,
Qt.ItemDataRole.WhatsThisRole,
Qt.ItemDataRole.ToolTipRole,
):
}:
return ""

if role == Qt.ItemDataRole.SizeHintRole:
Expand All @@ -349,11 +349,11 @@ def data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole) -> A
if role == Qt.ItemDataRole.FontRole:
return QFont()

if role in (
if role in {
Qt.ItemDataRole.BackgroundRole,
Qt.ItemDataRole.ForegroundRole,
Qt.ItemDataRole.DecorationRole,
):
}:
return QColor()

return QVariant()
Expand Down Expand Up @@ -395,7 +395,7 @@ def _fm_step_data(

if role == Qt.ItemDataRole.FontRole:
data_name = FM_STEP_COLUMNS[index.column()]
if data_name in [ids.STDOUT, ids.STDERR] and file_has_content(
if data_name in {ids.STDOUT, ids.STDERR} and file_has_content(
index.data(FileRole)
):
font = QFont()
Expand All @@ -404,7 +404,7 @@ def _fm_step_data(

if role == Qt.ItemDataRole.ForegroundRole:
data_name = FM_STEP_COLUMNS[index.column()]
if data_name in [ids.STDOUT, ids.STDERR] and file_has_content(
if data_name in {ids.STDOUT, ids.STDERR} and file_has_content(
index.data(FileRole)
):
return QColor(Qt.GlobalColor.blue)
Expand All @@ -418,18 +418,18 @@ def _fm_step_data(

if role == Qt.ItemDataRole.DisplayRole:
data_name = FM_STEP_COLUMNS[index.column()]
if data_name in [ids.MAX_MEMORY_USAGE]:
if data_name in {ids.MAX_MEMORY_USAGE}:
data = node.data
bytes_: str | None = data.get(data_name) # type: ignore
if bytes_:
return byte_with_unit(float(bytes_))

if data_name in [ids.STDOUT, ids.STDERR]:
if data_name in {ids.STDOUT, ids.STDERR}:
if not file_has_content(index.data(FileRole)):
return "-"
return "View" if data_name in node.data else QVariant()

if data_name in [DURATION]:
if data_name in {DURATION}:
start_time = node.data.get(ids.START_TIME)
if start_time is None:
return QVariant()
Expand All @@ -444,7 +444,7 @@ def _fm_step_data(

if role == FileRole:
data_name = FM_STEP_COLUMNS[index.column()]
if data_name in [ids.STDOUT, ids.STDERR]:
if data_name in {ids.STDOUT, ids.STDERR}:
return node.data.get(data_name, QVariant())

if role == RealIens:
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/simulation/run_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def mouseMoveEvent(self, event: QMouseEvent | None) -> None:
index = self.indexAt(event.pos())
if index.isValid():
data_name = FM_STEP_COLUMNS[index.column()]
if data_name in [ids.STDOUT, ids.STDERR] and file_has_content(
if data_name in {ids.STDOUT, ids.STDERR} and file_has_content(
index.data(FileRole)
):
self.setCursor(Qt.CursorShape.PointingHandCursor)
Expand Down
4 changes: 2 additions & 2 deletions src/ert/gui/tools/plot/plot_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,10 +267,10 @@ def _updateCustomizer(
x_axis_type = PlotContext.UNKNOWN_AXIS
y_axis_type = PlotContext.UNKNOWN_AXIS

if plot_widget.name in [ENSEMBLE, STATISTICS]:
if plot_widget.name in {ENSEMBLE, STATISTICS}:
x_axis_type = preferred_x_axis_format
y_axis_type = PlotContext.VALUE_AXIS
elif plot_widget.name in [DISTRIBUTION, CROSS_ENSEMBLE_STATISTICS]:
elif plot_widget.name in {DISTRIBUTION, CROSS_ENSEMBLE_STATISTICS}:
y_axis_type = PlotContext.VALUE_AXIS
elif plot_widget.name == HISTOGRAM:
x_axis_type = PlotContext.VALUE_AXIS
Expand Down
5 changes: 2 additions & 3 deletions src/ert/plugins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def inner(*args: P.args, **kwargs: P.kwargs) -> Any:
res = func(*args, **kwargs)
if (
func.__name__
in [
in {
"installable_jobs",
"job_documentation",
"installable_workflow_jobs",
Expand All @@ -30,10 +30,9 @@ def inner(*args: P.args, **kwargs: P.kwargs) -> Any:
"ecl100_config_path",
"ecl300_config_path",
"flow_config_path",
"help_links",
"site_config_lines",
"activate_script",
]
}
and res is not None
):
return PluginResponse(
Expand Down
4 changes: 2 additions & 2 deletions src/ert/resources/forward_models/res/script/ecl_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def __contains__(self, version: str) -> bool:
if version in self._config[Keys.versions]:
return True

return self.default_version is not None and version in [None, Keys.default]
return self.default_version is not None and version in {None, Keys.default}

def get_eclrun_env(self) -> dict[str, str] | None:
if "eclrun_env" in self._config:
Expand All @@ -108,7 +108,7 @@ def default_version(self) -> str | None:
return self._config.get(Keys.default_version)

def _get_version(self, version_arg: str | None) -> str:
if version_arg in [None, Keys.default]:
if version_arg in {None, Keys.default}:
version = self.default_version
else:
version = version_arg
Expand Down
6 changes: 3 additions & 3 deletions src/ert/resources/forward_models/res/script/ecl_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,10 @@ def _is_unsmry(base: str, path: str) -> bool:
if "." not in path:
return False
splitted = path.split(".")
return splitted[-2].endswith(base) and splitted[-1].lower() in [
return splitted[-2].endswith(base) and splitted[-1].lower() in {
"unsmry",
"funsmry",
]
}

base = basepath.name
candidates: list[str] = list(
Expand Down Expand Up @@ -268,7 +268,7 @@ def __init__(
# Dechipher the ecl_case argument.
input_arg = ecl_case
(_, ext) = os.path.splitext(input_arg)
if ext and ext in [".data", ".DATA"]:
if ext and ext in {".data", ".DATA"}:
data_file = input_arg
elif input_arg.islower():
data_file = input_arg + ".data"
Expand Down
12 changes: 6 additions & 6 deletions src/ert/run_models/base_run_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,10 +436,10 @@ def _current_progress(self) -> tuple[float, int]:

if all_realizations:
for real in all_realizations.values():
if real["status"] in [
if real["status"] in {
REALIZATION_STATE_FINISHED,
REALIZATION_STATE_FAILED,
]:
}:
done_realizations += 1

realization_progress = float(done_realizations) / len(
Expand Down Expand Up @@ -503,10 +503,10 @@ async def run_monitor(
async with Monitor(ee_config.get_connection_info()) as monitor:
logger.debug("connected")
async for event in monitor.track(heartbeat_interval=0.1):
if type(event) in (
if type(event) in {
EESnapshot,
EESnapshotUpdate,
):
}:
event = cast(EESnapshot | EESnapshotUpdate, event)
await asyncio.get_running_loop().run_in_executor(
None,
Expand All @@ -515,10 +515,10 @@ async def run_monitor(
iteration,
)

if event.snapshot.get(STATUS) in [
if event.snapshot.get(STATUS) in {
ENSEMBLE_STATE_STOPPED,
ENSEMBLE_STATE_FAILED,
]:
}:
logger.debug(
"observed evaluation stopped event, signal done"
)
Expand Down
2 changes: 1 addition & 1 deletion src/ert/run_models/everest_run_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,7 +699,7 @@ def _slug(entity: str) -> str:

def send_snapshot_event(self, event: Event, iteration: int) -> None:
super().send_snapshot_event(event, iteration)
if type(event) in (EESnapshot, EESnapshotUpdate):
if type(event) in {EESnapshot, EESnapshotUpdate}:
newstatus = self._simulation_status(self.get_current_snapshot())
if self.status != newstatus: # No change in status
self._sim_callback(newstatus)
Expand Down
2 changes: 1 addition & 1 deletion src/ert/shared/net_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def _bind_socket(
f"error msg is: {err_info.strerror}"
) from err_info
except OSError as err_info:
if err_info.errno in (48, 98):
if err_info.errno in {48, 98}:
raise PortAlreadyInUseException(
f"Port {port} already in use."
) from err_info
Expand Down
2 changes: 1 addition & 1 deletion src/everest/bin/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ def _get_jobs_status(progress):
job_progress[job_idx] = JobProgress(name=job["name"])
realization = int(job["realization"])
status = job["status"]
if status in [JOB_RUNNING, JOB_SUCCESS, JOB_FAILURE]:
if status in {JOB_RUNNING, JOB_SUCCESS, JOB_FAILURE}:
job_progress[job_idx].status[status].append(realization)
return job_progress.values()

Expand Down
Loading

0 comments on commit 6ce4714

Please sign in to comment.