Skip to content

Commit

Permalink
Fix ruff preview rule PLC1901
Browse files Browse the repository at this point in the history
This commit makes the code base ruff PLC1901 compliant. This is related
to empty string comparison.
  • Loading branch information
jonathan-eq committed Apr 2, 2024
1 parent ef492f0 commit f4433dc
Show file tree
Hide file tree
Showing 40 changed files with 84 additions and 79 deletions.
2 changes: 1 addition & 1 deletion src/ert/config/_option_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def option_dict(option_list: Sequence[str], offset: int) -> Dict[str, str]:
for option_pair in option_list[offset:]:
if len(option_pair.split(":")) == 2:
key, val = option_pair.split(":")
if val != "" and key != "":
if val and key:
result[key] = val
else:
raise ConfigValidationError.with_context(
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 @@ -70,7 +70,7 @@ def from_keyword(cls, summary_keyword: str) -> _SummaryType:
"S": cls.SEGMENT,
"W": cls.WELL,
}
if summary_keyword == "":
if not summary_keyword:
raise ValueError("Got empty summary keyword")
if any(special in summary_keyword for special in SPECIAL_KEYWORDS):
return cls.OTHER
Expand Down
2 changes: 1 addition & 1 deletion src/ert/config/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def from_config_list(
)
)
file_extension = out_file.suffix[1:].upper()
if out_file.suffix == "":
if not out_file.suffix:
errors.append(
ConfigValidationError.with_context(
f"Missing extension for field output file '{out_file}', "
Expand Down
2 changes: 1 addition & 1 deletion src/ert/config/queue_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ def _validate_queue_driver_settings(
queue_system_options: List[Tuple[str, str]], queue_type: str, throw_error: bool
) -> None:
for option_name, option_value in queue_system_options:
if option_value == "": # This is equivalent to the option not being set
if not option_value: # This is equivalent to the option not being set
continue
elif option_name in queue_memory_options[queue_type]:
option_format = queue_memory_usage_formats[queue_type]
Expand Down
6 changes: 3 additions & 3 deletions src/ert/gui/ertwidgets/checklist.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,14 +112,14 @@ def modelChanged(self):

self.filterList(self._search_box.filter())

def filterList(self, _filter):
def filterList(self, _filter: str):
_filter = _filter.lower()

for index in range(0, self._list.count()):
item = self._list.item(index)
text = str(item.text()).lower()
text = item.text().lower()

if _filter == "" or _filter in text:
if not _filter or _filter in text:
item.setHidden(False)
else:
item.setHidden(True)
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/ertwidgets/ensemblelist.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def addItem(self):
parent=self,
)
new_ensemble_name = dialog.showAndTell()
if new_ensemble_name != "":
if new_ensemble_name:
ensemble = self.storage.create_experiment(
parameters=self.ert_config.ensemble_config.parameter_configuration,
responses=self.ert_config.ensemble_config.response_configuration,
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/ertwidgets/models/activerealizationsmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def __init__(self, ensemble_size: int):
self._custom = False

def setValue(self, value: str):
if value is None or value.strip() == "" or value == self.getDefaultValue():
if not value or not value.strip() or value == self.getDefaultValue():
self._custom = False
ValueModel.setValue(self, self.getDefaultValue())
else:
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/ertwidgets/models/targetensemblemodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def __init__(

def setValue(self, value: str):
"""Set a new target ensemble"""
if value is None or value.strip() == "" or value == self.getDefaultValue():
if not value or not value.strip() or value == self.getDefaultValue():
self._custom = False
ValueModel.setValue(self, self.getDefaultValue())
else:
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/ertwidgets/models/text_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def __init__(
super().__init__(self.getDefaultValue())

def setValue(self, value: str):
if value is None or value.strip() == "" or value == self.getDefaultValue():
if not value or not value.strip() or value == self.getDefaultValue():
ValueModel.setValue(self, self.getDefaultValue())
else:
ValueModel.setValue(self, value)
Expand Down
8 changes: 4 additions & 4 deletions src/ert/gui/ertwidgets/pathchooser.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def __init__(self, model):
self.setLayout(layout)
self.getPathFromModel()

def isPathValid(self, path) -> Tuple[bool, str]:
def isPathValid(self, path: str) -> Tuple[bool, str]:
path = path.strip()
path_exists = os.path.exists(path)
is_file = os.path.isfile(path)
Expand All @@ -74,7 +74,7 @@ def isPathValid(self, path) -> Tuple[bool, str]:
valid = True
message = ""

if path == "":
if not path:
if self._model.pathIsRequired():
valid = False
message = PathChooser.REQUIRED_FIELD_MSG
Expand Down Expand Up @@ -127,15 +127,15 @@ def selectPath(self):
current_directory = self.getPath()

if self._model.pathMustBeAFile():
current_directory: tuple(str, str) = QFileDialog.getOpenFileName(
current_directory: tuple[str, str] = QFileDialog.getOpenFileName(
self, "Select a file path", current_directory
)[0]
else:
current_directory: str = QFileDialog.getExistingDirectory(
self, "Select a directory", current_directory
)

if current_directory != "":
if current_directory:
if not self._model.pathMustBeAbsolute():
cwd = os.getcwd()
match = re.match(cwd + "/(.*)", current_directory)
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/ertwidgets/searchbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def enterSearch(self):

def exitSearch(self):
"""Called when the line edit looses focus"""
if str(self.text()) == "":
if not self.text():
self.presentSearch()

def focusInEvent(self, focus_event):
Expand Down
4 changes: 2 additions & 2 deletions src/ert/gui/ertwidgets/stringbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ def emitChange(self, q_string):

def stringBoxChanged(self):
"""Called whenever the contents of the editline changes."""
text = str(self.text())
if text == "":
text = self.text()
if not text:
text = None

self._model.setValue(text)
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/ertwidgets/validateddialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def validateName(self, value):
this function and call valid() and notValid(msg)."""
value = str(value)

if value == "":
if not value:
self.notValid("Can not be empty!")
elif value.find(" ") != -1:
self.notValid("No spaces allowed!")
Expand Down
4 changes: 2 additions & 2 deletions src/ert/gui/ertwidgets/validationsupport.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,10 @@ def hideEvent(hide_event):

validation_target.hideEvent = hideEvent

def setValidationMessage(self, message, validation_type=WARNING):
def setValidationMessage(self, message: str, validation_type=WARNING):
"""Add a warning or information icon to the widget with a tooltip"""
message = message.strip()
if message == "":
if not message:
self._validation_type = None
self._validation_message = None
self._error_popup.hide()
Expand Down
30 changes: 15 additions & 15 deletions src/ert/gui/plottery/plot_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def __init__(
self._enabled = enabled
self._is_copy = False

def copyStyleFrom(self, other, copy_enabled_state=False):
def copyStyleFrom(self, other: "PlotStyle", copy_enabled_state=False):
self.color = other.color
self.alpha = other.alpha
self.line_style = other._line_style
Expand All @@ -34,65 +34,65 @@ def copyStyleFrom(self, other, copy_enabled_state=False):
if copy_enabled_state:
self.setEnabled(other.isEnabled())

def isEnabled(self):
def isEnabled(self) -> bool:
return self._enabled

def setEnabled(self, enabled):
def setEnabled(self, enabled: bool):
self._enabled = enabled

def isVisible(self):
return self.line_style != "" or self.marker != ""
def isVisible(self) -> bool:
return self.line_style or self.marker

@property
def name(self):
def name(self) -> str:
return self._name

@name.setter
def name(self, name):
self._name = name

@property
def color(self):
def color(self) -> str:
return self._color

@color.setter
def color(self, color):
self._color = color

@property
def alpha(self):
def alpha(self) -> float:
return self._alpha

@alpha.setter
def alpha(self, alpha):
self._alpha = max(min(alpha, 1.0), 0.0)

@property
def marker(self):
def marker(self) -> str:
return self._marker if self._marker is not None else ""

@marker.setter
def marker(self, marker):
def marker(self, marker: str):
self._marker = marker

@property
def line_style(self):
def line_style(self) -> str:
return self._line_style if self._line_style is not None else ""

@line_style.setter
def line_style(self, line_style):
def line_style(self, line_style: str):
self._line_style = line_style

@property
def width(self):
def width(self) -> float:
return self._width

@width.setter
def width(self, width):
def width(self, width: float):
self._width = max(width, 0.0)

@property
def size(self):
def size(self) -> float:
return self._size

@size.setter
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/plottery/plots/ensemble.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def _plotLines(
):
style = plot_config.defaultStyle()

if len(data) == 1 and style.marker == "":
if len(data) == 1 and not style.marker:
style.marker = "."

if is_date_supported:
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/plottery/plots/observations.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def cap_size(line_with):
return 0 if line_with == 0 else math.log(line_with, 1.2) + 3

# line style set to 'off' toggles errorbar visibility
if style.line_style == "":
if not style.line_style:
style.width = 0

axes.errorbar(
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/simulation/ensemble_smoother_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def getSimulationArguments(self) -> Arguments:
realizations=self._active_realizations_field.text(),
experiment_name=(
self._name_field.text()
if self._name_field.text() != ""
if self._name_field.text()
else self._name_field.placeholderText()
),
)
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/simulation/iterated_ensemble_smoother_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def getSimulationArguments(self):
num_iterations=self._num_iterations_spinner.value(),
experiment_name=(
self._name_field.text()
if self._name_field.text() != ""
if self._name_field.text()
else self._name_field.placeholderText()
),
)
2 changes: 1 addition & 1 deletion src/ert/gui/simulation/multiple_data_assimilation_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def getSimulationArguments(self):
prior_ensemble=self._ensemble_selector.currentText(),
experiment_name=(
self._name_field.text()
if self._name_field.text() != ""
if self._name_field.text()
else self._name_field.placeholderText()
),
)
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/simulation/single_test_run_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def __init__(self, run_path: str, notifier: ErtNotifier):
def getSimulationArguments(self):
experiment_name = (
self._name_field.text()
if self._name_field.text() != ""
if self._name_field.text()
else self._name_field.placeholderText()
)

Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/tools/plot/customize/customization_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def addLineEdit(self, attribute_name, title, tool_tip=None, placeholder=""):

def getter(self):
value = str(self[attribute_name].text())
if value == "":
if not value:
value = None
return value

Expand Down
20 changes: 12 additions & 8 deletions src/ert/gui/tools/plot/style_chooser.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import List, Optional, Tuple

from qtpy.QtWidgets import QComboBox, QDoubleSpinBox, QHBoxLayout, QLabel, QWidget

from ert.gui.plottery import PlotStyle
Expand Down Expand Up @@ -48,7 +50,7 @@
MARKER_HEXAGON1 = ("Hexagon 1", "h")
MARKER_HEXAGON2 = ("Hexagon 2", "H")

MARKERS = [
MARKERS: List[Tuple[str, Optional[str]]] = [
MARKER_OFF,
MARKER_X,
MARKER_CIRCLE,
Expand All @@ -69,7 +71,7 @@ def __init__(self, line_style_set=STYLESET_DEFAULT):
QWidget.__init__(self)
self._style = PlotStyle("StyleChooser internal style")

self._styles = (
self._styles: List[Tuple[str, Optional[str]]] = (
STYLES["default"]
if line_style_set not in STYLES
else STYLES[line_style_set]
Expand Down Expand Up @@ -140,15 +142,15 @@ def getItemSizes(self):
size_spinner_width,
)

def _findLineStyleIndex(self, line_style):
def _findLineStyleIndex(self, line_style: str):
for index, style in enumerate(self._styles):
if (style[1] == line_style) or (style[1] is None and line_style == ""):
if (style[1] == line_style) or (style[1] is None and not line_style):
return index
return -1

def _findMarkerStyleIndex(self, marker):
def _findMarkerStyleIndex(self, marker: str):
for index, style in enumerate(MARKERS):
if (style[1] == marker) or (style[1] is None and marker == ""):
if (style[1] == marker) or (style[1] is None and not marker):
return index
return -1

Expand All @@ -161,8 +163,10 @@ def _updateLineStyleAndMarker(self, line_style, marker, thickness, size):
def _updateStyle(self):
self.marker_chooser.setEnabled(self.line_chooser.currentText() != "Area")

line_style = self.line_chooser.itemData(self.line_chooser.currentIndex())
marker_style = self.marker_chooser.itemData(self.marker_chooser.currentIndex())
line_style: str = self.line_chooser.itemData(self.line_chooser.currentIndex())
marker_style: str = self.marker_chooser.itemData(
self.marker_chooser.currentIndex()
)
thickness = float(self.thickness_spinner.value())
size = float(self.size_spinner.value())

Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/tools/plot/widgets/clearable_line_edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def focusInEvent(self, focus_event):

def focusOutEvent(self, focus_event):
QLineEdit.focusOutEvent(self, focus_event)
if str(QLineEdit.text(self)) == "":
if not QLineEdit.text(self):
self.showPlaceholder()

def keyPressEvent(self, key_event):
Expand Down
Loading

0 comments on commit f4433dc

Please sign in to comment.