diff --git a/pyproject.toml b/pyproject.toml index 5e2560294..9640b0665 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,6 +17,7 @@ select = [ "NPY", # numpy specific rules "C4", # flake8-comprehensions "PD", # pandas-vet + "UP", # pyupgrade ] ignore = ["PLW2901", # redefined-loop-name "PLR2004", # magic-value-comparison diff --git a/python/docs/examples/avg_pressure.py b/python/docs/examples/avg_pressure.py index db97178a7..dd37e441e 100755 --- a/python/docs/examples/avg_pressure.py +++ b/python/docs/examples/avg_pressure.py @@ -40,9 +40,9 @@ def avg_pressure(p, sw, pv, region, region_id, result): if __name__ == "__main__": case = sys.argv[1] - grid = Grid("%s.EGRID" % case) - rst_file = ResdataRestartFile(grid, "%s.UNRST" % case) - init_file = ResdataFile("%s.INIT" % case) + grid = Grid(f"{case}.EGRID") + rst_file = ResdataRestartFile(grid, f"{case}.UNRST") + init_file = ResdataFile(f"{case}.INIT") # Create PORV keyword where all the inactive cells have been removed. pv = grid.compressed_kw_copy(init_file["PORV"][0]) diff --git a/python/resdata/__init__.py b/python/resdata/__init__.py index a369d228a..4f57dc4f2 100644 --- a/python/resdata/__init__.py +++ b/python/resdata/__init__.py @@ -95,9 +95,7 @@ class ResdataPrototype(Prototype): lib = _dlopen_resdata() def __init__(self, prototype, bind=True): - super(ResdataPrototype, self).__init__( - ResdataPrototype.lib, prototype, bind=bind - ) + super().__init__(ResdataPrototype.lib, prototype, bind=bind) from .rd_type import ResDataType, ResdataTypeEnum diff --git a/python/resdata/geometry/cpolyline.py b/python/resdata/geometry/cpolyline.py index fcd64949e..8eefbfb14 100644 --- a/python/resdata/geometry/cpolyline.py +++ b/python/resdata/geometry/cpolyline.py @@ -40,14 +40,14 @@ class CPolyline(BaseCClass): def __init__(self, name=None, init_points=()): c_ptr = self._alloc_new(name) - super(CPolyline, self).__init__(c_ptr) + super().__init__(c_ptr) for xc, yc in init_points: self.addPoint(xc, yc) @classmethod def createFromXYZFile(cls, filename, name=None): if not os.path.isfile(filename): - raise IOError("No such file:%s" % filename) + raise OSError(f"No such file:{filename}") polyline = cls._fread_alloc_irap(filename) if not name is None: @@ -56,10 +56,10 @@ def createFromXYZFile(cls, filename, name=None): def __str__(self): name = self.getName() - str = "%s [" % name if name else "[" + str = f"{name} [" if name else "[" for index, p in enumerate(self): - str += "(%g,%g)" % p + str += "({:g},{:g})".format(*p) if index < len(self) - 1: str += "," str += "]" @@ -73,7 +73,7 @@ def __len__(self): def __getitem__(self, index): if not isinstance(index, int): - raise TypeError("Index argument must be integer. Index:%s invalid" % index) + raise TypeError(f"Index argument must be integer. Index:{index} invalid") if index < 0: index += len(self) @@ -119,7 +119,7 @@ def __radd__(self, other): return copy def __eq__(self, other): - if super(CPolyline, self).__eq__(other): + if super().__eq__(other): return True else: return self._equal(other) @@ -142,7 +142,7 @@ def extendToBBox(self, bbox, start=True): intersections = GeometryTools.rayPolygonIntersections(p1, ray_dir, bbox) if intersections: p2 = intersections[0][1] - name = "Extend:%s" % self.getName() if self.getName() else None + name = f"Extend:{self.getName()}" if self.getName() else None return CPolyline(name=name, init_points=[(p1[0], p1[1]), p2]) else: diff --git a/python/resdata/geometry/cpolyline_collection.py b/python/resdata/geometry/cpolyline_collection.py index 52d2f44f0..27c9ad546 100644 --- a/python/resdata/geometry/cpolyline_collection.py +++ b/python/resdata/geometry/cpolyline_collection.py @@ -37,7 +37,7 @@ class CPolylineCollection(BaseCClass): def __init__(self): c_ptr = self._alloc_new() - super(CPolylineCollection, self).__init__(c_ptr) + super().__init__(c_ptr) self.parent_ref = None def __contains__(self, name): @@ -68,7 +68,7 @@ def __getitem__(self, index): if index in self: return self._get(index) else: - raise KeyError("No polyline named:%s" % index) + raise KeyError(f"No polyline named:{index}") else: raise TypeError("The index argument must be string or integer") @@ -92,7 +92,7 @@ def addPolyline(self, polyline, name=None): name = polyline.getName() if name and name in self: - raise KeyError("The polyline collection already has an object:%s" % name) + raise KeyError(f"The polyline collection already has an object:{name}") if polyline.isReference(): self._add_polyline(polyline, False) @@ -102,7 +102,7 @@ def addPolyline(self, polyline, name=None): def createPolyline(self, name=None): if name and name in self: - raise KeyError("The polyline collection already has an object:%s" % name) + raise KeyError(f"The polyline collection already has an object:{name}") polyline = self._create_polyline(name) polyline.setParent(parent=self) diff --git a/python/resdata/geometry/geo_pointset.py b/python/resdata/geometry/geo_pointset.py index c60cb81fb..aa0fe8961 100644 --- a/python/resdata/geometry/geo_pointset.py +++ b/python/resdata/geometry/geo_pointset.py @@ -14,10 +14,10 @@ class GeoPointset(BaseCClass): def __init__(self, external_z=False): c_ptr = self._alloc(external_z) if c_ptr: - super(GeoPointset, self).__init__(c_ptr) + super().__init__(c_ptr) else: ext = "external" if external_z else "internal" - raise ValueError("Failed to construct GeoPointset with %s_z." % ext) + raise ValueError(f"Failed to construct GeoPointset with {ext}_z.") @staticmethod def fromSurface(surface): @@ -42,7 +42,7 @@ def __getitem__(self, key): ) else: # TODO implement slicing? - raise ValueError("Index must be int, not %s." % type(key)) + raise ValueError(f"Index must be int, not {type(key)}.") def __len__(self): return self._get_size() diff --git a/python/resdata/geometry/geo_region.py b/python/resdata/geometry/geo_region.py index 54bb00ba4..15b6f2f5a 100644 --- a/python/resdata/geometry/geo_region.py +++ b/python/resdata/geometry/geo_region.py @@ -45,18 +45,16 @@ def __init__(self, pointset, preselect=False): self._preselect = bool(preselect) c_ptr = self._alloc(pointset, self._preselect) if c_ptr: - super(GeoRegion, self).__init__(c_ptr) + super().__init__(c_ptr) else: - raise ValueError( - "Could not construct GeoRegion from pointset %s." % pointset - ) + raise ValueError(f"Could not construct GeoRegion from pointset {pointset}.") def getActiveList(self): return self._get_index_list() def _assert_polygon(self, polygon): if not isinstance(polygon, CPolyline): - raise ValueError("Need to select with a CPolyline, not %s." % type(polygon)) + raise ValueError(f"Need to select with a CPolyline, not {type(polygon)}.") def _construct_cline(self, line): """Takes a line ((x1,y1), (x2,y2)) and returns two double[2]* but diff --git a/python/resdata/geometry/geometry_tools.py b/python/resdata/geometry/geometry_tools.py index 8d15d599d..eeb34fd2f 100644 --- a/python/resdata/geometry/geometry_tools.py +++ b/python/resdata/geometry/geometry_tools.py @@ -3,7 +3,7 @@ from math import sqrt -class GeometryTools(object): +class GeometryTools: EPSILON = 0.000001 @staticmethod @@ -400,8 +400,7 @@ def connectPolylines(polyline, target_polyline): if len(d_list) == 0: raise ValueError( - "Polyline %s can not be extended to %s" - % (polyline.getName(), target_polyline.getName()) + f"Polyline {polyline.getName()} can not be extended to {target_polyline.getName()}" ) d_list.sort(key=lambda x: x[0]) diff --git a/python/resdata/geometry/polyline.py b/python/resdata/geometry/polyline.py index 1c7566802..a24cc68dd 100644 --- a/python/resdata/geometry/polyline.py +++ b/python/resdata/geometry/polyline.py @@ -3,9 +3,9 @@ from .geometry_tools import GeometryTools -class Polyline(object): +class Polyline: def __init__(self, name=None, init_points=None): - super(Polyline, self).__init__() + super().__init__() self.__name = name self.__points = [] if init_points: @@ -14,7 +14,7 @@ def __init__(self, name=None, init_points=None): def __str__(self): s = "Polyline:[ " for p in self: - s += "(%s,%s) " % (p[0], p[1]) + s += f"({p[0]},{p[1]}) " s += "]" return s diff --git a/python/resdata/geometry/surface.py b/python/resdata/geometry/surface.py index a361fa2a2..d5e9ca846 100644 --- a/python/resdata/geometry/surface.py +++ b/python/resdata/geometry/surface.py @@ -1,8 +1,7 @@ -from __future__ import division - """ Create a polygon """ + import os.path import ctypes @@ -67,18 +66,17 @@ def __init__( filename = str(filename) if os.path.isfile(filename): c_ptr = self._alloc(filename, True) - super(Surface, self).__init__(c_ptr) + super().__init__(c_ptr) else: - raise IOError('No such file "%s".' % filename) + raise OSError(f'No such file "{filename}".') else: s_args = [nx, ny, xinc, yinc, xstart, ystart, angle] if None in s_args: raise ValueError( - "Missing argument for creating surface, all values must be set, was: %s" - % str(s_args) + f"Missing argument for creating surface, all values must be set, was: {str(s_args)}" ) c_ptr = self._new(*s_args) - super(Surface, self).__init__(c_ptr) + super().__init__(c_ptr) def __eq__(self, other): """ @@ -203,7 +201,7 @@ def __setitem__(self, index, value): self._iset_zvalue(index, value) else: - raise TypeError("Invalid index type:%s - must be integer" % index) + raise TypeError(f"Invalid index type:{index} - must be integer") def __getitem__(self, index): if isinstance(index, int): @@ -218,7 +216,7 @@ def __getitem__(self, index): "Invalid index:%d - valid range [0,%d)" % (index, len(self)) ) else: - raise TypeError("Invalid index type:%s - must be integer" % index) + raise TypeError(f"Invalid index type:{index} - must be integer") def getXY(self, index): """Gets the index'th (x,y) coordinate""" @@ -232,7 +230,7 @@ def getXY(self, index): ) index = idx else: - raise TypeError("Invalid index type:%s - must be integer" % index) + raise TypeError(f"Invalid index type:{index} - must be integer") x = ctypes.c_double() y = ctypes.c_double() @@ -252,13 +250,9 @@ def getPointset(self): def _assert_idx_or_i_and_j(self, idx, i, j): if idx is None: if i is None or j is None: - raise ValueError( - "idx is None, i and j must be ints, was %s and %s." % (i, j) - ) + raise ValueError(f"idx is None, i and j must be ints, was {i} and {j}.") elif i is not None or j is not None: - raise ValueError( - "idx is set, i and j must be None, was %s and %s." % (i, j) - ) + raise ValueError(f"idx is set, i and j must be None, was {i} and {j}.") def getXYZ(self, idx=None, i=None, j=None): """Returns a tuple of 3 floats, (x,y,z) for given global index, or i and j.""" diff --git a/python/resdata/geometry/xyz_io.py b/python/resdata/geometry/xyz_io.py index 90e3b09c9..e91084df1 100644 --- a/python/resdata/geometry/xyz_io.py +++ b/python/resdata/geometry/xyz_io.py @@ -2,19 +2,19 @@ from .polyline import Polyline -class XYZIo(object): +class XYZIo: @staticmethod def readXYZFile(path): """@rtype: Polyline""" if not os.path.exists(path): - raise IOError("Path does not exist '%s'!" % path) + raise OSError(f"Path does not exist '{path}'!") name = os.path.basename(path) polyline = Polyline(name=name) - with open(path, "r") as f: + with open(path) as f: for line in f: line = line.strip() if line: @@ -34,13 +34,13 @@ def readXYFile(path): """@rtype: Polyline""" if not os.path.exists(path): - raise IOError("Path does not exist '%s'!" % path) + raise OSError(f"Path does not exist '{path}'!") name = os.path.basename(path) polyline = Polyline(name=name) - with open(path, "r") as f: + with open(path) as f: for line in f: x, y = map(float, line.split()) polyline.addPoint(x, y) @@ -54,4 +54,4 @@ def saveXYFile(polyline, filename): """ with open(filename, "w") as fileH: for p in polyline: - fileH.write("%g %g\n" % (p[0], p[1])) + fileH.write(f"{p[0]:g} {p[1]:g}\n") diff --git a/python/resdata/gravimetry/rd_grav.py b/python/resdata/gravimetry/rd_grav.py index 49aed935a..9cda2c9b9 100644 --- a/python/resdata/gravimetry/rd_grav.py +++ b/python/resdata/gravimetry/rd_grav.py @@ -68,7 +68,7 @@ def __init__(self, grid: Grid, init_file: ResdataFile): self.init_file = init_file # Inhibit premature garbage collection of init_file c_ptr = self._grav_alloc(grid, init_file) - super(ResdataGrav, self).__init__(c_ptr) + super().__init__(c_ptr) self.dispatch = { "FIP": self.add_survey_FIP, diff --git a/python/resdata/gravimetry/rd_subsidence.py b/python/resdata/gravimetry/rd_subsidence.py index 4597dbab5..5198ddd10 100644 --- a/python/resdata/gravimetry/rd_subsidence.py +++ b/python/resdata/gravimetry/rd_subsidence.py @@ -60,7 +60,7 @@ def __init__(self, grid, init_file): """ self.init_file = init_file # Inhibit premature garbage collection of init_file c_ptr = self._alloc(grid, init_file) - super(ResdataSubsidence, self).__init__(c_ptr) + super().__init__(c_ptr) def __contains__(self, survey_name): return self._has_survey(survey_name) @@ -96,10 +96,10 @@ def eval_geertsma( region=None, ): if not base_survey in self: - raise KeyError("No such survey: %s" % base_survey) + raise KeyError(f"No such survey: {base_survey}") if monitor_survey is not None and not monitor_survey in self: - raise KeyError("No such survey: %s" % monitor_survey) + raise KeyError(f"No such survey: {monitor_survey}") return self._eval_geertsma( base_survey, @@ -124,10 +124,10 @@ def eval_geertsma_rporv( region=None, ): if not base_survey in self: - raise KeyError("No such survey: %s" % base_survey) + raise KeyError(f"No such survey: {base_survey}") if monitor_survey is not None and not monitor_survey in self: - raise KeyError("No such survey: %s" % monitor_survey) + raise KeyError(f"No such survey: {monitor_survey}") return self._eval_geertsma_rporv( base_survey, @@ -174,10 +174,10 @@ def eval( The argument @compressibility is the total reservoir compressibility. """ if not base_survey in self: - raise KeyError("No such survey: %s" % base_survey) + raise KeyError(f"No such survey: {base_survey}") if not monitor_survey in self: - raise KeyError("No such survey: %s" % monitor_survey) + raise KeyError(f"No such survey: {monitor_survey}") return self._eval( base_survey, diff --git a/python/resdata/grid/cell.py b/python/resdata/grid/cell.py index cf8c850c4..f4d80c965 100644 --- a/python/resdata/grid/cell.py +++ b/python/resdata/grid/cell.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -class Cell(object): +class Cell: def __init__(self, grid, global_index): self._grid = grid self._idx = global_index @@ -68,7 +68,7 @@ def __contains__(self, coord): """ if len(coord) != 3: raise ValueError( - "Cell contains takes a triple (x,y,z), was given %s." % coord + f"Cell contains takes a triple (x,y,z), was given {coord}." ) x, y, z = coord return self._grid._cell_contains(self._idx, x, y, z) @@ -102,7 +102,7 @@ def corners(self): def __repr__(self): act = "active" if self.active else "inactive" - pos = "(%.3f, %.3f, %.3f)" % self.coordinate + pos = "({:.3f}, {:.3f}, {:.3f})".format(*self.coordinate) cnt = "%d, %d, %d, %s, %s, grid=%s" % ( self.i, self.j, @@ -112,4 +112,4 @@ def __repr__(self): self._grid.get_name(), ) - return "Cell(%s)" % cnt + return f"Cell({cnt})" diff --git a/python/resdata/grid/faults/fault.py b/python/resdata/grid/faults/fault.py index 296682a0d..fdeb8dbbc 100644 --- a/python/resdata/grid/faults/fault.py +++ b/python/resdata/grid/faults/fault.py @@ -7,7 +7,7 @@ from .fault_segments import FaultSegment, SegmentMap -class FaultLayer(object): +class FaultLayer: def __init__(self, grid, K): assert isinstance(K, int) self.__grid = grid @@ -143,7 +143,7 @@ def process_segments(self): ################################################################# -class Fault(object): +class Fault: allowed_faces = ["X", "Y", "Z", "I", "J", "K", "X-", "Y-", "Z-", "I-", "J-", "K-"] def __init__(self, grid, name): @@ -154,7 +154,7 @@ def __init__(self, grid, name): (self.nx, self.ny, self.nz, nactive) = grid.getDims() def __str__(self): - return "Fault:%s" % self.__name + return f"Fault:{self.__name}" def __getitem__(self, K): if not self.hasLayer(K): @@ -166,8 +166,7 @@ def __len__(self): return len(self.__layer_map) def __iter__(self): - for layer in self.__layer_list: - yield layer + yield from self.__layer_list def has_layer(self, K): return K in self.__layer_map @@ -197,7 +196,7 @@ def create_segment(self, I1, I2, J1, J2, face): def add_record(self, I1, I2, J1, J2, K1, K2, face): if not face in Fault.allowed_faces: - raise ValueError("Invalid face:%s" % face) + raise ValueError(f"Invalid face:{face}") if I1 > I2: raise ValueError("Invalid I1 I2 indices") @@ -224,13 +223,13 @@ def add_record(self, I1, I2, J1, J2, K1, K2, face): raise ValueError("Invalid K2:%d" % K2) if face in ["X", "I"] and I1 != I2: - raise ValueError("For face:%s we must have I1 == I2" % face) + raise ValueError(f"For face:{face} we must have I1 == I2") if face in ["Y", "J"] and J1 != J2: - raise ValueError("For face:%s we must have J1 == J2" % face) + raise ValueError(f"For face:{face} we must have J1 == J2") if face in ["Z", "K"] and K1 != K2: - raise ValueError("For face:%s we must have K1 == K2" % face) + raise ValueError(f"For face:{face} we must have K1 == K2") # ----------------------------------------------------------------- @@ -257,7 +256,7 @@ def get_neighbor_cells(self): def get_polyline(self, k): layer = self[k] - return layer.getPolyline(name="Polyline[%s]" % self.getName()) + return layer.getPolyline(name=f"Polyline[{self.getName()}]") def get_ij_polyline(self, k): layer = self[k] @@ -396,7 +395,7 @@ def extend_to_b_box(self, bbox, k, start=True): intersections = GeometryTools.rayPolygonIntersections(p1, ray_dir, bbox) if intersections: p2 = intersections[0][1] - name = "Extend:%s" % self.getName() if self.getName() else None + name = f"Extend:{self.getName()}" if self.getName() else None return CPolyline(name=name, init_points=[(p1[0], p1[1]), p2]) else: diff --git a/python/resdata/grid/faults/fault_block.py b/python/resdata/grid/faults/fault_block.py index 9ad0f6090..e8641bcab 100644 --- a/python/resdata/grid/faults/fault_block.py +++ b/python/resdata/grid/faults/fault_block.py @@ -7,7 +7,7 @@ from resdata.geometry import Polyline, GeometryTools, CPolylineCollection -class FaultBlockCell(object): +class FaultBlockCell: def __init__(self, i, j, k, x, y, z): self.i = i self.j = j diff --git a/python/resdata/grid/faults/fault_block_layer.py b/python/resdata/grid/faults/fault_block_layer.py index aa095b07f..88ca0d014 100644 --- a/python/resdata/grid/faults/fault_block_layer.py +++ b/python/resdata/grid/faults/fault_block_layer.py @@ -1,4 +1,3 @@ -from __future__ import print_function from cwrap import BaseCClass from resdata.util.util import monkey_the_camel @@ -55,7 +54,7 @@ class FaultBlockLayer(BaseCClass): def __init__(self, grid, k): c_ptr = self._alloc(grid, k) if c_ptr: - super(FaultBlockLayer, self).__init__(c_ptr) + super().__init__(c_ptr) else: raise ValueError("Invalid input - failed to create FaultBlockLayer") @@ -152,7 +151,7 @@ def add_block(self, block_id=None): block_id = self.getNextID() if block_id in self: - raise KeyError("Layer already contains block with ID:%s" % block_id) + raise KeyError(f"Layer already contains block with ID:{block_id}") else: return self._add_block(block_id).setParent(self) diff --git a/python/resdata/grid/faults/fault_collection.py b/python/resdata/grid/faults/fault_collection.py index 7930b3f61..a9aa4bacc 100644 --- a/python/resdata/grid/faults/fault_collection.py +++ b/python/resdata/grid/faults/fault_collection.py @@ -12,12 +12,12 @@ def dequote(s): if s[0] == s[-1]: return s[1:-1] else: - raise ValueError("s[0] != s[-1], s[0]={}, s[-1]={}".format(s[0], s[-1])) + raise ValueError(f"s[0] != s[-1], s[0]={s[0]}, s[-1]={s[-1]}") else: return s -class FaultCollection(object): +class FaultCollection: def __init__(self, grid=None, *file_list): self.__fault_list = [] self.__fault_map = {} @@ -64,10 +64,10 @@ def add_fault(self, fault): def split_line(self, line): tmp = line.split() if not tmp[-1] == "/": - raise ValueError("Line:%s does not end with /" % line) + raise ValueError(f"Line:{line} does not end with /") if len(tmp) != 9: - raise ValueError("Line:%s not correct number of items" % line) + raise ValueError(f"Line:{line} not correct number of items") fault_name = dequote(tmp[0]) I1 = int(tmp[1]) - 1 diff --git a/python/resdata/grid/faults/fault_line.py b/python/resdata/grid/faults/fault_line.py index 395029128..5f38e8ec2 100644 --- a/python/resdata/grid/faults/fault_line.py +++ b/python/resdata/grid/faults/fault_line.py @@ -7,7 +7,7 @@ from .fault_segments import FaultSegment -class FaultLine(object): +class FaultLine: def __init__(self, grid, k): self.__grid = grid self.__k = k diff --git a/python/resdata/grid/faults/fault_segments.py b/python/resdata/grid/faults/fault_segments.py index 919662a06..24ca47441 100644 --- a/python/resdata/grid/faults/fault_segments.py +++ b/python/resdata/grid/faults/fault_segments.py @@ -1,9 +1,7 @@ -from __future__ import print_function - from resdata.util.util import monkey_the_camel -class FaultSegment(object): +class FaultSegment: def __init__(self, C1, C2): self.__C1 = C1 self.__C2 = C2 @@ -53,7 +51,7 @@ def __repr__(self): return "%d -> %d" % (self.__C1, self.__C2) -class SegmentMap(object): +class SegmentMap: def __init__(self): self.__segment_map = {} self.__count_map = {} diff --git a/python/resdata/grid/faults/layer.py b/python/resdata/grid/faults/layer.py index 7f5f6f61f..99dc5ef80 100644 --- a/python/resdata/grid/faults/layer.py +++ b/python/resdata/grid/faults/layer.py @@ -49,7 +49,7 @@ class Layer(BaseCClass): def __init__(self, nx, ny): c_ptr = self._alloc(nx, ny) if c_ptr: - super(Layer, self).__init__(c_ptr) + super().__init__(c_ptr) else: raise ValueError("Invalid input - no Layer object created") @@ -65,7 +65,7 @@ def __unpack_index(self, index): (i, j) = index except TypeError as err: raise ValueError( - "Index:%s is invalid - must have two integers" % str(index) + f"Index:{str(index)} is invalid - must have two integers" ) from err self._assert_ij(i, j) diff --git a/python/resdata/grid/rd_grid.py b/python/resdata/grid/rd_grid.py index 493a2f042..ff31311a3 100644 --- a/python/resdata/grid/rd_grid.py +++ b/python/resdata/grid/rd_grid.py @@ -231,7 +231,7 @@ def load_from_grdecl(cls, filename): return Grid.create(specgrid, zcorn, coord, actnum, mapaxes) else: - raise IOError("No such file:%s" % filename) + raise OSError(f"No such file:{filename}") @classmethod def load_from_file(cls, filename): @@ -316,9 +316,9 @@ def __init__(self, filename, apply_mapaxes=True): """ c_ptr = self._fread_alloc(filename, apply_mapaxes) if c_ptr: - super(Grid, self).__init__(c_ptr) + super().__init__(c_ptr) else: - raise IOError("Loading grid from:%s failed" % filename) + raise OSError(f"Loading grid from:{filename} failed") def free(self): self._free() @@ -336,7 +336,7 @@ def __repr__(self): """ name = self._nicename() if name: - name = '"%s", ' % name + name = f'"{name}", ' g_size = self.getGlobalSize() a_size = self.getNumActive() xyz_s = "%dx%dx%d" % (self.getNX(), self.getNY(), self.getNZ()) @@ -496,8 +496,7 @@ def __iter__(self): def cells(self, active=False): """Iterator over all the (active) cells""" if not active: - for c in self: - yield c + yield from self else: for i in range(self.get_num_active()): yield self.cell(active_index=i) @@ -1065,7 +1064,7 @@ def get_lgr(self, lgr_key): lgr = self._get_named_lgr(lgr_key) if lgr is None: - raise KeyError("No such LGR: %s" % lgr_key) + raise KeyError(f"No such LGR: {lgr_key}") lgr.setParent(self) return lgr @@ -1148,7 +1147,7 @@ def create_kw(self, array, kw_name, pack): elif dtype == np.float64: type = ResDataType.RD_DOUBLE else: - sys.exit("Do not know how to create rd_kw from type:%s" % dtype) + sys.exit(f"Do not know how to create rd_kw from type:{dtype}") size = self.getNumActive() if pack else self.getGlobalSize() diff --git a/python/resdata/grid/rd_grid_generator.py b/python/resdata/grid/rd_grid_generator.py index 167569111..88e60ad06 100644 --- a/python/resdata/grid/rd_grid_generator.py +++ b/python/resdata/grid/rd_grid_generator.py @@ -177,7 +177,7 @@ def create_zcorn( zcorn = cls.__create_faults(nx, ny, nz, zcorn, drop) if z != escape_origo_shift[2] + nz * dz: - raise ValueError("%f != %f" % (z, escape_origo_shift[2] + nz * dz)) + raise ValueError(f"{z:f} != {escape_origo_shift[2] + nz * dz:f}") cls.assert_zcorn(nx, ny, nz, zcorn) return construct_floatKW("ZCORN", zcorn) @@ -495,8 +495,9 @@ def assert_actnum(cls, nx, ny, nz, actnum): if set(actnum) - {0, 1}: raise AssertionError( - "Expected ACTNUM to consist of 0's and 1's, was %s." - % ", ".join(map(str, set(actnum))) + "Expected ACTNUM to consist of 0's and 1's, was {}.".format( + ", ".join(map(str, set(actnum))) + ) ) @classmethod @@ -734,7 +735,7 @@ def assert_ijk_bounds(cls, dims, ijk_bounds): if not (isinstance(bound[0], int) and isinstance(bound[1], int)): raise TypeError( "Expected bound to consist of two integers, ", - "was %s (%s)" % (str(bound), str((map(type, bound)))), + f"was {str(bound)} ({str(map(type, bound))})", ) if not (0 <= bound[0] <= bound[1] < n): @@ -750,7 +751,7 @@ def assert_ijk_bounds(cls, dims, ijk_bounds): def assert_decomposition_change(cls, ijk_bounds, decomposition_change): if sum(list(zip(*ijk_bounds))[0]) % 2 == 1 and not decomposition_change: raise ValueError( - "The subgrid defined by %s " % str(ijk_bounds) + f"The subgrid defined by {str(ijk_bounds)} " + "will cause an unintended decomposition change. " + "Either change one of the lower bounds by 1 " + "or activate decomposition_change." diff --git a/python/resdata/grid/rd_region.py b/python/resdata/grid/rd_region.py index add2e7bec..f2529a9dc 100644 --- a/python/resdata/grid/rd_region.py +++ b/python/resdata/grid/rd_region.py @@ -317,7 +317,7 @@ def __init__(self, grid, preselect): self.grid = grid self.active_index = False c_ptr = self._alloc(grid, preselect) - super(ResdataRegion, self).__init__(c_ptr) + super().__init__(c_ptr) def free(self): self._free() @@ -551,8 +551,7 @@ def select_equal(self, rd_kw, value, intersect=False): """ if not rd_kw.data_type.is_int(): raise ValueError( - "The select_equal method must have an integer valued keyword - got:%s" - % rd_kw.type_name() + f"The select_equal method must have an integer valued keyword - got:{rd_kw.type_name()} ) self._select_equal(rd_kw, value) @@ -564,8 +563,7 @@ def deselect_equal(self, rd_kw, value): """ if not rd_kw.data_type.is_int(): raise ValueError( - "The select_equal method must have an integer valued keyword - got:%s" - % rd_kw.type_name() + f"The select_equal method must have an integer valued keyword - got:{rd_kw.type_name()}" ) self._deselect_equal(rd_kw, value) diff --git a/python/resdata/rd_type.py b/python/resdata/rd_type.py index 7af86c47e..6b79197e6 100644 --- a/python/resdata/rd_type.py +++ b/python/resdata/rd_type.py @@ -64,7 +64,7 @@ def __init__(self, type_enum=None, element_size=None, type_name=None): else: c_ptr = self._alloc(type_enum, element_size) - super(ResDataType, self).__init__(c_ptr) + super().__init__(c_ptr) def _assert_valid_arguments(self, type_enum, element_size, type_name): if type_name is not None: @@ -148,7 +148,7 @@ def create_from_type_name(cls, name): return ResDataType(type_name=name) # Enables one to fetch a type as ResDataType.RD_XXXX - class classproperty(object): + class classproperty: def __init__(self, fget): self.fget = fget diff --git a/python/resdata/rd_util.py b/python/resdata/rd_util.py index 1454330fd..a4d5b8f87 100644 --- a/python/resdata/rd_util.py +++ b/python/resdata/rd_util.py @@ -10,8 +10,6 @@ functions from rd_util.c which are not bound to any class type. """ -from __future__ import absolute_import - import ctypes from cwrap import BaseCEnum @@ -99,7 +97,7 @@ class FileMode(BaseCEnum): # ----------------------------------------------------------------- -class ResdataUtil(object): +class ResdataUtil: _get_num_cpu = ResdataPrototype("int rd_get_num_cpu(char*)", bind=False) _get_file_type = ResdataPrototype( "rd_file_enum rd_get_file_type(char*, bool*, int*)", bind=False @@ -149,7 +147,7 @@ def inspect_extension(filename): def report_step(filename): report_step = ResdataUtil._get_report_step(filename) if report_step < 0: - raise ValueError("Could not infer report step from: %s" % filename) + raise ValueError(f"Could not infer report step from: {filename}") return report_step diff --git a/python/resdata/resfile/fortio.py b/python/resdata/resfile/fortio.py index e261e15b9..d0a8903fd 100644 --- a/python/resdata/resfile/fortio.py +++ b/python/resdata/resfile/fortio.py @@ -100,7 +100,7 @@ def __init__( """ read_modes = (FortIO.READ_MODE, FortIO.APPEND_MODE, FortIO.READ_AND_WRITE_MODE) if mode in read_modes and not os.path.exists(file_name): - raise IOError('No such file "%s".' % file_name) + raise OSError(f'No such file "{file_name}".') if mode == FortIO.READ_MODE: c_pointer = self._open_reader(file_name, fmt_file, endian_flip_header) elif mode == FortIO.WRITE_MODE: @@ -114,8 +114,8 @@ def __init__( self.__mode = mode if not c_pointer: - raise IOError('Failed to open FortIO file "%s".' % file_name) - super(FortIO, self).__init__(c_pointer) + raise OSError(f'Failed to open FortIO file "{file_name}".') + super().__init__(c_pointer) def close(self): if self: @@ -136,7 +136,7 @@ def truncate(self, size=None): size = self.getPosition() if not self._truncate(size): - raise IOError("Truncate of fortran filehandle:%s failed" % self.filename()) + raise OSError(f"Truncate of fortran filehandle:{self.filename()} failed") def filename(self): return self._filename() @@ -163,7 +163,7 @@ def free(self): self.close() -class FortIOContextManager(object): +class FortIOContextManager: def __init__(self, fortio): self.__fortio = fortio diff --git a/python/resdata/resfile/rd_3d_file.py b/python/resdata/resfile/rd_3d_file.py index c5bbc2c64..c94de1eed 100644 --- a/python/resdata/resfile/rd_3d_file.py +++ b/python/resdata/resfile/rd_3d_file.py @@ -4,10 +4,10 @@ class Resdata3DFile(ResdataFile): def __init__(self, grid, filename, flags=0): self.grid = grid - super(Resdata3DFile, self).__init__(filename, flags) + super().__init__(filename, flags) def __getitem__(self, index): - return_arg = super(Resdata3DFile, self).__getitem__(index) + return_arg = super().__getitem__(index) kw_list = return_arg if isinstance(return_arg, list) else [return_arg] # Go through all the keywords and try inplace promotion to Resdata3DKW diff --git a/python/resdata/resfile/rd_3dkw.py b/python/resdata/resfile/rd_3dkw.py index 5c0e6e825..8f3b1bbf4 100644 --- a/python/resdata/resfile/rd_3dkw.py +++ b/python/resdata/resfile/rd_3dkw.py @@ -53,7 +53,7 @@ class Resdata3DKW(ResdataKW): def __init__(self, kw, grid, value_type, default_value=0, global_active=False): size = grid.getGlobalSize() if global_active else grid.getNumActive() - super(Resdata3DKW, self).__init__(kw, size, value_type) + super().__init__(kw, size, value_type) self.grid = grid self.global_active = global_active self.setDefault(default_value) @@ -70,7 +70,7 @@ def read_grdecl(cls, grid, fileH, kw, strict=True, rd_type=None): See the base class ResdataKW.read_grdecl() for more documentation. """ - kw = super(Resdata3DKW, cls).read_grdecl(fileH, kw, strict, rd_type) + kw = super().read_grdecl(fileH, kw, strict, rd_type) Resdata3DKW.castFromKW(kw, grid) return kw @@ -96,7 +96,7 @@ def __getitem__(self, index): else: index = self.grid.get_active_index(ijk=index) - return super(Resdata3DKW, self).__getitem__(index) + return super().__getitem__(index) def __setitem__(self, index, value): """Set the value of at index [g] or [i,j,k]. @@ -120,7 +120,7 @@ def __setitem__(self, index, value): else: index = self.grid.get_active_index(ijk=index) - return super(Resdata3DKW, self).__setitem__(index, value) + return super().__setitem__(index, value) @classmethod def cast_from_kw(cls, kw, grid, default_value=0): diff --git a/python/resdata/resfile/rd_file.py b/python/resdata/resfile/rd_file.py index c2e6ac5d0..58805fa32 100644 --- a/python/resdata/resfile/rd_file.py +++ b/python/resdata/resfile/rd_file.py @@ -132,8 +132,7 @@ def report_list(self): report_steps.append(int(matchObj.group(1))) else: raise TypeError( - 'Tried get list of report steps from file "%s" - which is not a restart file' - % fname + f'Tried get list of report steps from file "{fname}" - which is not a restart file' ) from err return report_steps @@ -150,7 +149,7 @@ def file_report_list(cls, filename): def __repr__(self): fn = self.getFilename() wr = ", read/write" if self._writable() else "" - return self._create_repr('"%s"%s' % (fn, wr)) + return self._create_repr(f'"{fn}"{wr}') def __init__(self, filename, flags=FileMode.DEFAULT, index_filename=None): """ @@ -182,9 +181,9 @@ def __init__(self, filename, flags=FileMode.DEFAULT, index_filename=None): c_ptr = self._fast_open(filename, index_filename, flags) if c_ptr is None: - raise IOError('Failed to open file "%s"' % filename) + raise OSError(f'Failed to open file "{filename}"') else: - super(ResdataFile, self).__init__(c_ptr) + super().__init__(c_ptr) self.global_view = self._get_global_view() self.global_view.setParent(self) @@ -214,8 +213,8 @@ def save_kw(self, kw): if self._writable(): self._save_kw(kw) else: - raise IOError( - 'save_kw: the file "%s" has been opened read only.' % self.getFilename() + raise OSError( + f'save_kw: the file "{self.getFilename()}" has been opened read only.' ) def __len__(self): @@ -231,7 +230,7 @@ def free(self): def block_view(self, kw, kw_index): if not kw in self: - raise KeyError('No such keyword "%s".' % kw) + raise KeyError(f'No such keyword "{kw}".') ls = self.global_view.numKeywords(kw) idx = kw_index if idx < 0: @@ -366,15 +365,11 @@ def restart_get_kw(self, kw_name, dtime, copy=False): else: return kw elif self.has_kw(kw_name): - raise IndexError( - 'Does not have keyword "%s" at time:%s.' % (kw_name, dtime) - ) + raise IndexError(f'Does not have keyword "{kw_name}" at time:{dtime}.') else: - raise KeyError('Keyword "%s" not recognized.' % kw_name) + raise KeyError(f'Keyword "{kw_name}" not recognized.') else: - raise IndexError( - 'Does not have keyword "%s" at time:%s.' % (kw_name, dtime) - ) + raise IndexError(f'Does not have keyword "{kw_name}" at time:{dtime}.') @property def size(self): @@ -560,10 +555,10 @@ def fwrite(self, fortio): def write_index(self, index_file_name): if not self or not self._write_index(index_file_name): - raise IOError("Failed to write index file:%s" % index_file_name) + raise OSError(f"Failed to write index file:{index_file_name}") -class ResdataFileContextManager(object): +class ResdataFileContextManager: def __init__(self, rd_file): self.__rd_file = rd_file diff --git a/python/resdata/resfile/rd_file_view.py b/python/resdata/resfile/rd_file_view.py index e4abc9977..f7fc47f8f 100644 --- a/python/resdata/resfile/rd_file_view.py +++ b/python/resdata/resfile/rd_file_view.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import, division, print_function, unicode_literals from six import string_types from cwrap import BaseCClass from resdata.util.util import monkey_the_camel @@ -45,7 +44,7 @@ def __repr__(self): def iget_named_kw(self, kw_name, index): if not kw_name in self: - raise KeyError("No such keyword: %s" % kw_name) + raise KeyError(f"No such keyword: {kw_name}") if index >= self.numKeywords(kw_name): raise IndexError("Too large index: %d" % index) @@ -107,7 +106,7 @@ def __getitem__(self, index): kw_list.append(self.iget_named_kw(kw_index, index)) return kw_list else: - raise KeyError("Unrecognized keyword:'%s'" % index) + raise KeyError(f"Unrecognized keyword:'{index}'") else: raise TypeError("Index must be integer or string (keyword)") @@ -130,7 +129,7 @@ def block_view2(self, start_kw, stop_kw, start_index): idx = start_index if start_kw: if not start_kw in self: - raise KeyError("The keyword:%s is not in file" % start_kw) + raise KeyError(f"The keyword:{start_kw} is not in file") ls = self.numKeywords(start_kw) if idx < 0: @@ -141,7 +140,7 @@ def block_view2(self, start_kw, stop_kw, start_index): ) if stop_kw and not stop_kw in self: - raise KeyError("The keyword:%s is not in file" % stop_kw) + raise KeyError(f"The keyword:{stop_kw} is not in file") view = self._create_block_view2(start_kw, stop_kw, idx) view.setParent(parent=self) @@ -151,7 +150,7 @@ def block_view(self, kw, kw_index): num = self.numKeywords(kw) if num == 0: - raise KeyError("Unknown keyword: %s" % kw) + raise KeyError(f"Unknown keyword: {kw}") idx = kw_index if idx < 0: diff --git a/python/resdata/resfile/rd_init_file.py b/python/resdata/resfile/rd_init_file.py index 8771c45f4..90ce37b0a 100644 --- a/python/resdata/resfile/rd_init_file.py +++ b/python/resdata/resfile/rd_init_file.py @@ -6,7 +6,7 @@ class ResdataInitFile(Resdata3DFile): def __init__(self, grid, filename, flags=FileMode.DEFAULT): file_type, report_step, fmt_file = ResdataFile.getFileType(filename) if file_type == FileType.INIT: - super(ResdataInitFile, self).__init__(grid, filename, flags) + super().__init__(grid, filename, flags) else: err = 'The input filename "%s" does not correspond to an init file.' err += " Please follow the Eclipse naming conventions." diff --git a/python/resdata/resfile/rd_kw.py b/python/resdata/resfile/rd_kw.py index c57c1bf57..7fe5a3ee9 100644 --- a/python/resdata/resfile/rd_kw.py +++ b/python/resdata/resfile/rd_kw.py @@ -196,7 +196,7 @@ class ResdataKW(BaseCClass): @classmethod def createCReference(cls, c_ptr, parent=None): - rd_kw = super(ResdataKW, cls).createCReference(c_ptr, parent=parent) + rd_kw = super().createCReference(c_ptr, parent=parent) if rd_kw is None: raise ValueError("Failed to create ResdataKW instance") @@ -205,7 +205,7 @@ def createCReference(cls, c_ptr, parent=None): @classmethod def createPythonObject(cls, c_ptr): - rd_kw = super(ResdataKW, cls).createPythonObject(c_ptr) + rd_kw = super().createPythonObject(c_ptr) if rd_kw is None: raise ValueError("Failed to create ResdataKW instance") @@ -314,7 +314,7 @@ def read_grdecl(cls, fileH, kw, strict=True, rd_type=None): cfile = CFILE(fileH) if kw and len(kw) > 8: raise TypeError( - "Sorry keyword:%s is too long, must be eight characters or less." % kw + f"Sorry keyword:{kw} is too long, must be eight characters or less." ) if rd_type is None: @@ -326,12 +326,11 @@ def read_grdecl(cls, fileH, kw, strict=True, rd_type=None): rd_type = warn_and_cast_data_type(rd_type) if not isinstance(rd_type, ResDataType): - raise TypeError("Expected ResDataType, was: %s" % type(rd_type)) + raise TypeError(f"Expected ResDataType, was: {type(rd_type)}") if not rd_type in [ResDataType.RD_FLOAT, ResDataType.RD_INT]: raise ValueError( - "The type:%s is invalid when loading keyword:%s" - % (rd_type.type_name, kw) + f"The type:{rd_type.type_name} is invalid when loading keyword:{kw}" ) return cls._load_grdecl(cfile, kw, strict, rd_type) @@ -377,10 +376,10 @@ def free(self): def __repr__(self): si = len(self) nm = self.getName() - mm = "type=%s" % str(self.data_type) + mm = f"type={str(self.data_type)}" if self.isNumeric(): mi, ma = self.getMinMax() - mm = "min=%.2f, max=%.2f" % (mi, ma) + mm = f"min={mi:.2f}, max={ma:.2f}" ad = self._ad_str() fmt = 'ResdataKW(size=%d, name="%s", %s) %s' return fmt % (si, nm, mm, ad) @@ -402,10 +401,10 @@ def __init__(self, name, size, data_type): data_type = warn_and_cast_data_type(data_type) if not isinstance(data_type, ResDataType): - raise TypeError("Expected an ResDataType, received: %s" % type(data_type)) + raise TypeError(f"Expected an ResDataType, received: {type(data_type)}") c_ptr = self._alloc_new(name, size, data_type) - super(ResdataKW, self).__init__(c_ptr) + super().__init__(c_ptr) self.__private_init() def __private_init(self): @@ -436,7 +435,7 @@ def __private_init(self): elif self.data_type.is_string(): self.str_fmt = "%" + str(self.data_type.element_size) + "s" else: - raise ValueError("Unknown ResDataType (%s)!" % self.data_type.type_name) + raise ValueError(f"Unknown ResDataType ({self.data_type.type_name})!") def sub_copy(self, offset, count, new_header=None): """ @@ -695,8 +694,7 @@ def sum(self, mask=None, force_active=False): return sum else: raise ValueError( - 'The keyword "%s" is of string type - sum is not implemented' - % self.getName() + f'The keyword "{self.getName()}" is of string type - sum is not implemented' ) return mask.sum_kw(self, force_active) @@ -950,7 +948,7 @@ def get_min_max(self): self._max_min_int(ctypes.byref(max_), ctypes.byref(min_)) else: raise TypeError( - "min_max property not defined for keywords of type: %s" % self.type + f"min_max property not defined for keywords of type: {self.type}" ) return (min_.value, max_.value) @@ -1201,9 +1199,7 @@ def scatter_copy(self, actnum): def safe_div(self, divisor): if not len(self) == len(divisor): - raise ValueError( - "Length mismatch between %s and %s" % (self.name, divisor.name) - ) + raise ValueError(f"Length mismatch between {self.name} and {divisor.name}") if not self.is_numeric(): raise TypeError("The self keyword must be of numeric type") diff --git a/python/resdata/resfile/rd_restart_file.py b/python/resdata/resfile/rd_restart_file.py index bc4c86945..fca970d6e 100644 --- a/python/resdata/resfile/rd_restart_file.py +++ b/python/resdata/resfile/rd_restart_file.py @@ -34,7 +34,7 @@ def __init__(self, kw_arg=None, rst_view=None): else: c_ptr = self._alloc(rst_view, -1) - super(ResdataRestartHead, self).__init__(c_ptr) + super().__init__(c_ptr) def free(self): self._free() @@ -74,11 +74,10 @@ def __init__(self, grid, filename, flags=FileMode.DEFAULT): FileType.UNIFIED_RESTART, ]: raise ValueError( - 'The input filename "%s" does not correspond to a restart file. Please follow the Eclipse naming conventions' - % filename + f'The input filename "{filename}" does not correspond to a restart file. Please follow the Eclipse naming conventions' ) - super(ResdataRestartFile, self).__init__(grid, filename, flags) + super().__init__(grid, filename, flags) self.rst_headers = None if file_type == FileType.RESTART: self.is_unified = False diff --git a/python/resdata/rft/rd_rft.py b/python/resdata/rft/rd_rft.py index 778ad5539..fe33cb138 100644 --- a/python/resdata/rft/rd_rft.py +++ b/python/resdata/rft/rd_rft.py @@ -59,7 +59,7 @@ class ResdataRFT(BaseCClass): def __init__(self, name, type_string, date, days): c_ptr = self._alloc(name, type_string, CTime(date), days) - super(ResdataRFT, self).__init__(c_ptr) + super().__init__(c_ptr) def free(self): self._free() @@ -67,7 +67,7 @@ def free(self): def __repr__(self): rs = [] rs.append("completed_cells = %d" % len(self)) - rs.append("date = %s" % self.getDate()) + rs.append(f"date = {self.getDate()}") if self.is_RFT(): rs.append("RFT") if self.is_PLT(): @@ -205,7 +205,7 @@ class ResdataRFTFile(BaseCClass): def __init__(self, case): c_ptr = self._load(case) - super(ResdataRFTFile, self).__init__(c_ptr) + super().__init__(c_ptr) def __len__(self): return self._get_size(None, CTime(-1)) @@ -272,7 +272,7 @@ def get(self, well_name, date): Raise Exception if not found. """ if self.size(well=well_name, date=date) == 0: - raise KeyError("No RFT for well:%s at %s" % (well_name, date)) + raise KeyError(f"No RFT for well:{well_name} at {date}") rft = self._get_rft(well_name, CTime(date)) rft.setParent(self) diff --git a/python/resdata/rft/rd_rft_cell.py b/python/resdata/rft/rd_rft_cell.py index bcbdcf78d..e6e4c15f5 100644 --- a/python/resdata/rft/rd_rft_cell.py +++ b/python/resdata/rft/rd_rft_cell.py @@ -65,7 +65,7 @@ class ResdataRFTCell(RFTCell): def __init__(self, i, j, k, depth, pressure, swat, sgas): c_ptr = self._alloc_RFT(i, j, k, depth, pressure, swat, sgas) - super(ResdataRFTCell, self).__init__(c_ptr) + super().__init__(c_ptr) @property def swat(self): @@ -144,7 +144,7 @@ def __init__( gas_flowrate, water_flowrate, ) - super(ResdataPLTCell, self).__init__(c_ptr) + super().__init__(c_ptr) @property def orat(self): diff --git a/python/resdata/rft/well_trajectory.py b/python/resdata/rft/well_trajectory.py index 20d7722d7..45b08ddf1 100644 --- a/python/resdata/rft/well_trajectory.py +++ b/python/resdata/rft/well_trajectory.py @@ -31,7 +31,7 @@ def _parse_point(point): tvd = float(point[3]) except ValueError as err: raise UserWarning( - "Error: Failed to extract data from line %s\n" % str(point) + f"Error: Failed to extract data from line {str(point)}\n" ) from err zone = None if len(point) > 4: @@ -43,7 +43,7 @@ class WellTrajectory: def __init__(self, filename): self._points = [] if not isfile(filename): - raise IOError('No such file "%s"' % filename) + raise OSError(f'No such file "{filename}"') with open(filename) as fileH: for line in fileH.readlines(): @@ -66,4 +66,4 @@ def __repr__(self): return "WellTrajectory(len=%d)" % len(self) def __str__(self): - return "WellTrajectory(%s)" % str(self._points) + return f"WellTrajectory({str(self._points)})" diff --git a/python/resdata/summary/rd_cmp.py b/python/resdata/summary/rd_cmp.py index 20f41c13c..77458a99a 100644 --- a/python/resdata/summary/rd_cmp.py +++ b/python/resdata/summary/rd_cmp.py @@ -3,7 +3,7 @@ from .rd_sum import Summary -class ResdataCase(object): +class ResdataCase: def __init__(self, case): self.case = case @@ -48,10 +48,10 @@ def cmp_summary_vector(self, other, key, sample=100): diff_sum = sum(abs(diff_data)) return (diff_sum, ref_sum) else: - raise KeyError("Key:%s was not present in both cases" % key) + raise KeyError(f"Key:{key} was not present in both cases") -class ResdataCmp(object): +class ResdataCmp: def __init__(self, test_case, ref_case): """Class to compare to simulation cases with Eclipse formatted result files. diff --git a/python/resdata/summary/rd_npv.py b/python/resdata/summary/rd_npv.py index 638be8c1c..c048adfc8 100644 --- a/python/resdata/summary/rd_npv.py +++ b/python/resdata/summary/rd_npv.py @@ -7,7 +7,7 @@ from .rd_sum import Summary -class NPVParseKey(object): +class NPVParseKey: def __init__(self, eclNPV): self.baseCase = eclNPV.baseCase self.NPV = eclNPV @@ -20,10 +20,10 @@ def __call__(self, matchObject): self.NPV.addKey(key, var) return var + "[i]" else: - raise ValueError("Sorry - the key: %s is not a total key - aborting" % key) + raise ValueError(f"Sorry - the key: {key} is not a total key - aborting") -class NPVPriceVector(object): +class NPVPriceVector: def __init__(self, argList): self.dateList = [] if isinstance(argList, list): @@ -109,10 +109,10 @@ def eval(self, date): index2 = index return self.evalDate(self.dateList[index], date) else: - raise ValueError("Input date:%s before start of vector" % date) + raise ValueError(f"Input date:{date} before start of vector") -class ResdataNPV(object): +class ResdataNPV: sumKeyRE = re.compile(r"[\[]([\w:,]+)[\]]") def __init__(self, baseCase): @@ -120,7 +120,7 @@ def __init__(self, baseCase): if sum: self.baseCase = sum else: - raise OSError("Failed to open summary case:%s" % baseCase) + raise OSError(f"Failed to open summary case:{baseCase}") self.expression = None self.keyList = {} self.start = None @@ -148,9 +148,7 @@ def add_key(self, key, var): def parse_expression(self, expression): self.keyList = {} if expression.count("[") != expression.count("]"): - raise ValueError( - "Expression:%s invalid - not matching [ and ]" % expression - ) + raise ValueError(f"Expression:{expression} invalid - not matching [ and ]") replaceKey = NPVParseKey(self) parsedExpression = self.sumKeyRE.sub(replaceKey, expression) @@ -162,20 +160,14 @@ def compile(self, expression): "trange = self.baseCase.timeRange(self.start, self.end, self.interval)\n" ) for key, var in self.keyList.items(): - self.code += '%s = self.baseCase.blockedProduction("%s", trange)\n' % ( - var, - key, - ) + self.code += f'{var} = self.baseCase.blockedProduction("{key}", trange)\n' self.code += "npv = 0\n" - self.code += ( - """ + self.code += f""" for i in range(len(trange) - 1): - npv += %s + npv += {parsedExpression} varDict[\"npv\"] = npv """ - % parsedExpression - ) def eval_npv(self): byteCode = compile(self.code, "", "exec") diff --git a/python/resdata/summary/rd_smspec_node.py b/python/resdata/summary/rd_smspec_node.py index 5460aae7b..8a8e908ec 100644 --- a/python/resdata/summary/rd_smspec_node.py +++ b/python/resdata/summary/rd_smspec_node.py @@ -34,7 +34,7 @@ class ResdataSMSPECNode(BaseCClass): _get_default = ResdataPrototype("float smspec_node_get_default(rd_smspec_node)") def __init__(self): - super(ResdataSMSPECNode, self).__init__(0) # null pointer + super().__init__(0) # null pointer raise NotImplementedError("Class can not be instantiated directly!") def cmp(self, other): diff --git a/python/resdata/summary/rd_sum.py b/python/resdata/summary/rd_sum.py index e6f489e46..a62aa3720 100644 --- a/python/resdata/summary/rd_sum.py +++ b/python/resdata/summary/rd_sum.py @@ -253,20 +253,20 @@ def __init__( load_case, join_string, include_restart, lazy_load, file_options ) if c_pointer is None: - raise IOError( - "Failed to create summary instance from argument:%s" % load_case + raise OSError( + f"Failed to create summary instance from argument:{load_case}" ) - super(Summary, self).__init__(c_pointer) + super().__init__(c_pointer) self._load_case = load_case @classmethod def load(cls, smspec_file, unsmry_file, key_join_string=":", include_restart=True): if not os.path.isfile(smspec_file): - raise IOError("No such file: %s" % smspec_file) + raise OSError(f"No such file: {smspec_file}") if not os.path.isfile(unsmry_file): - raise IOError("No such file: %s" % unsmry_file) + raise OSError(f"No such file: {unsmry_file}") data_files = StringList() data_files.append(unsmry_file) @@ -274,7 +274,7 @@ def load(cls, smspec_file, unsmry_file, key_join_string=":", include_restart=Tru smspec_file, data_files, key_join_string, include_restart ) if c_ptr is None: - raise IOError("Failed to create summary instance") + raise OSError("Failed to create summary instance") rd_sum = cls.createPythonObject(c_ptr) rd_sum._load_case = smspec_file @@ -282,12 +282,12 @@ def load(cls, smspec_file, unsmry_file, key_join_string=":", include_restart=Tru @classmethod def createCReference(cls, c_pointer, parent=None): - result = super(Summary, cls).createCReference(c_pointer, parent) + result = super().createCReference(c_pointer, parent) return result @classmethod def createPythonObject(cls, c_pointer): - result = super(Summary, cls).createPythonObject(c_pointer) + result = super().createPythonObject(c_pointer) return result @staticmethod @@ -387,12 +387,12 @@ def add_t_step(self, report_step, sim_days): """@rtype: SummaryTStep""" # report_step int if not isinstance(report_step, int): - raise TypeError("Parameter report_step should be int, was %r" % report_step) + raise TypeError(f"Parameter report_step should be int, was {report_step!r}") try: float(sim_days) except TypeError as err: raise TypeError( - "Parameter sim_days should be float, was %r" % sim_days + f"Parameter sim_days should be float, was {sim_days!r}" ) from err sim_seconds = sim_days * 24 * 60 * 60 @@ -479,7 +479,7 @@ def get_values(self, key, report_only=False): return values else: - raise KeyError("Summary object does not have key:%s" % key) + raise KeyError(f"Summary object does not have key:{key}") def _make_time_vector(self, time_index): time_points = TimeVector() @@ -511,7 +511,7 @@ def numpy_vector(self, key, time_index=None, report_only=False): """ if key not in self: - raise KeyError("No such key:%s" % key) + raise KeyError(f"No such key:{key}") if report_only: if time_index is None: @@ -701,8 +701,7 @@ def _compile_headers_list( k = int(nums[2]) - 1 if dims is None: raise ValueError( - "For key %s When using indexing i,j,k you must supply a valid value for the dims argument" - % key + f"For key {key} When using indexing i,j,k you must supply a valid value for the dims argument" ) num = i + j * dims[0] + k * dims[0] * dims[1] + 1 @@ -787,7 +786,7 @@ def last_value(self, key): instance with some extra time related information. """ if not key in self: - raise KeyError("No such key:%s" % key) + raise KeyError(f"No such key:{key}") return self._get_last_value(key) @@ -796,7 +795,7 @@ def first_value(self, key): Will return first value corresponding to @key. """ if not key in self: - raise KeyError("No such key:%s" % key) + raise KeyError(f"No such key:{key}") return self._get_first_value(key) @@ -862,7 +861,7 @@ def __contains__(self, key): def assert_key_valid(self, key): if not key in self: - raise KeyError("The summary key:%s was not recognized" % key) + raise KeyError(f"The summary key:{key} was not recognized") def __iter__(self): return iter(self.keys()) @@ -936,14 +935,13 @@ def get_interp(self, key, days=None, date=None): if self.check_sim_time(t): return self._get_general_var_from_sim_time(t, key) else: - raise ValueError("date:%s is outside range of simulation data" % date) + raise ValueError(f"date:{date} is outside range of simulation data") elif date is None: if self._check_sim_days(days): return self._get_general_var_from_sim_days(days, key) else: raise ValueError( - "days:%s is outside range of simulation: [%g,%g]" - % (days, self.first_day, self.sim_length) + f"days:{days} is outside range of simulation: [{self.first_day:g},{self.sim_length:g}]" ) else: raise ValueError("Must supply either days or date") @@ -1146,7 +1144,7 @@ def smspec_node(self, key): node = self._get_var_node(key).setParent(self) return node else: - raise KeyError("Summary case does not have key:%s" % key) + raise KeyError(f"Summary case does not have key:{key}") def unit(self, key): """ @@ -1480,7 +1478,7 @@ def solve_dates(self, key, value, rates_clamp_lower=True): See solveDays() for further details. """ if not key in self: - raise KeyError("Unrecognized key:%s" % key) + raise KeyError(f"Unrecognized key:{key}") if len(self) < 2: raise ValueError("Must have at least two elements to start solving") @@ -1571,7 +1569,7 @@ def solve_days(self, key, value, rates_clamp_lower=True): """ if not key in self: - raise KeyError("Unrecognized key:%s" % key) + raise KeyError(f"Unrecognized key:{key}") if len(self) < 2: raise ValueError("Must have at least two elements to start solving") @@ -1682,9 +1680,7 @@ def resample( new_case_name, time_points, lower_extrapolation, upper_extrapolation ) if new_case is None: - raise ValueError( - "Failed to create new resampled case:{}".format(new_case_name) - ) + raise ValueError(f"Failed to create new resampled case:{new_case_name}") return new_case diff --git a/python/resdata/summary/rd_sum_keyword_vector.py b/python/resdata/summary/rd_sum_keyword_vector.py index ce4c324d0..e249ac383 100644 --- a/python/resdata/summary/rd_sum_keyword_vector.py +++ b/python/resdata/summary/rd_sum_keyword_vector.py @@ -24,7 +24,7 @@ class SummaryKeyWordVector(BaseCClass): def __init__(self, rd_sum, add_keywords=False): c_pointer = self._alloc(rd_sum, add_keywords) - super(SummaryKeyWordVector, self).__init__(c_pointer) + super().__init__(c_pointer) def __getitem__(self, index): if index < 0: diff --git a/python/resdata/summary/rd_sum_node.py b/python/resdata/summary/rd_sum_node.py index 024bb661f..c4a0417d0 100644 --- a/python/resdata/summary/rd_sum_node.py +++ b/python/resdata/summary/rd_sum_node.py @@ -1,4 +1,4 @@ -class SummaryNode(object): +class SummaryNode: def __init__(self, report_step, days, date, mpl_date, value): """ SummaryNode is a 'struct' with a summary value and time. diff --git a/python/resdata/summary/rd_sum_tstep.py b/python/resdata/summary/rd_sum_tstep.py index 68699c078..54ac197f4 100644 --- a/python/resdata/summary/rd_sum_tstep.py +++ b/python/resdata/summary/rd_sum_tstep.py @@ -28,7 +28,7 @@ class SummaryTStep(BaseCClass): def __init__(self, report_step, mini_step, sim_days, smspec): sim_seconds = sim_days * 24 * 60 * 60 c_pointer = self._alloc(report_step, mini_step, sim_seconds, smspec) - super(SummaryTStep, self).__init__(c_pointer) + super().__init__(c_pointer) def get_sim_days(self): """@rtype: double""" @@ -49,13 +49,13 @@ def get_sim_time(self): def __getitem__(self, key): """@rtype: double""" if not key in self: - raise KeyError("Key '%s' is not available." % key) + raise KeyError(f"Key '{key}' is not available.") return self._get_from_key(key) def __setitem__(self, key, value): if not key in self: - raise KeyError("Key '%s' is not available." % key) + raise KeyError(f"Key '{key}' is not available.") self._set_from_key(key, value) diff --git a/python/resdata/summary/rd_sum_vector.py b/python/resdata/summary/rd_sum_vector.py index 362ab1217..5560668e9 100644 --- a/python/resdata/summary/rd_sum_vector.py +++ b/python/resdata/summary/rd_sum_vector.py @@ -1,11 +1,9 @@ -from __future__ import print_function - import warnings from .rd_sum_node import SummaryNode -class SummaryVector(object): +class SummaryVector: def __init__(self, parent, key, report_only=False): """ A summary vector with a vector of values and time. @@ -41,7 +39,7 @@ def __init__(self, parent, key, report_only=False): self.__values = None def __str__(self): - return "" % self.key + return f"" def __repr__(self): return "SummaryVector(key = %s, size = %d, unit = %s)" % ( @@ -174,7 +172,7 @@ def __getitem__(self, index): index += step return sub_vector - raise KeyError("Invalid index:%s - must have integer or slice." % index) + raise KeyError(f"Invalid index:{index} - must have integer or slice.") @property def first(self): diff --git a/python/resdata/util/test/debug_msg.py b/python/resdata/util/test/debug_msg.py index 9faac85ec..2fff34e07 100644 --- a/python/resdata/util/test/debug_msg.py +++ b/python/resdata/util/test/debug_msg.py @@ -5,4 +5,4 @@ def debug_msg(msg): record = inspect.stack()[1] frame = record[0] info = inspect.getframeinfo(frame) - return "FILE: %s LINE: %s Msg: %s" % (info.filename, info.lineno, msg) + return f"FILE: {info.filename} LINE: {info.lineno} Msg: {msg}" diff --git a/python/resdata/util/test/extended_testcase.py b/python/resdata/util/test/extended_testcase.py index 66c4a5375..5311386ba 100644 --- a/python/resdata/util/test/extended_testcase.py +++ b/python/resdata/util/test/extended_testcase.py @@ -20,16 +20,16 @@ def log_test(test): def wrapper(*args): - sys.stderr.write("starting: %s \n" % test.__name__) + sys.stderr.write(f"starting: {test.__name__} \n") test(*args) - sys.stderr.write("complete: %s \n" % test.__name__) + sys.stderr.write(f"complete: {test.__name__} \n") return wrapper -class _AssertNotRaisesContext(object): +class _AssertNotRaisesContext: def __init__(self, test_class): - super(_AssertNotRaisesContext, self).__init__() + super().__init__() self._test_class = test_class def __enter__(self): @@ -42,8 +42,7 @@ def __exit__(self, exc_type, exc_value, tb): except AttributeError: exc_name = str(exc_type) self._test_class.fail( - "Exception: %s raised\n%s" - % (exc_name, traceback.print_exception(exc_type, exc_value, tb)) + f"Exception: {exc_name} raised\n{traceback.print_exception(exc_type, exc_value, tb)}" ) return True @@ -60,7 +59,7 @@ class ExtendedTestCase(TestCase): def __init__(self, *args, **kwargs): installAbortSignals() - super(ExtendedTestCase, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def assertFloatEqual(self, first, second, msg=None, tolerance=1e-6): try: @@ -68,16 +67,11 @@ def assertFloatEqual(self, first, second, msg=None, tolerance=1e-6): diff = abs(f_first - f_second) scale = max(1, abs(first) + abs(second)) if msg is None: - msg = "Floats not equal: |%f - %f| > %g" % ( - f_first, - f_second, - tolerance, - ) + msg = f"Floats not equal: |{f_first:f} - {f_second:f}| > {tolerance:g}" self.assertTrue(diff < tolerance * scale, msg=msg) except TypeError: self.fail( - "Cannot compare as floats: %s (%s) and %s (%s)" - % (first, type(first), second, type(second)) + f"Cannot compare as floats: {first} ({type(first)}) and {second} ({type(second)})" ) def assertAlmostEqualList(self, first, second, msg=None, tolerance=1e-6): @@ -94,12 +88,11 @@ def assertImportable(self, module_name): __import__(module_name) except ImportError: tb = traceback.format_exc() - self.fail("Module %s not found!\n\nTrace:\n%s" % (module_name, str(tb))) + self.fail(f"Module {module_name} not found!\n\nTrace:\n{str(tb)}") except Exception: tb = traceback.format_exc() self.fail( - "Import of module %s caused errors!\n\nTrace:\n%s" - % (module_name, str(tb)) + f"Import of module {module_name} caused errors!\n\nTrace:\n{str(tb)}" ) def assertFilesAreEqual(self, first, second): @@ -112,19 +105,19 @@ def assertFilesAreNotEqual(self, first, second): def assertFileExists(self, path): if not os.path.exists(path) or not os.path.isfile(path): - self.fail("The file: %s does not exist!" % path) + self.fail(f"The file: {path} does not exist!") def assertDirectoryExists(self, path): if not os.path.exists(path) or not os.path.isdir(path): - self.fail("The directory: %s does not exist!" % path) + self.fail(f"The directory: {path} does not exist!") def assertFileDoesNotExist(self, path): if os.path.exists(path) and os.path.isfile(path): - self.fail("The file: %s exists!" % path) + self.fail(f"The file: {path} exists!") def assertDirectoryDoesNotExist(self, path): if os.path.exists(path) and os.path.isdir(path): - self.fail("The directory: %s exists!" % path) + self.fail(f"The directory: {path} exists!") def __filesAreEqual(self, first, second): buffer1 = open(first, "rb").read() # noqa: SIM115 @@ -148,14 +141,13 @@ def assertEnumIsFullyDefined( self.assertTrue( identifier in enum_class.__dict__, - "Enum does not have identifier: %s" % identifier, + f"Enum does not have identifier: {identifier}", ) class_value = enum_class.__dict__[identifier] self.assertEqual( class_value, value, - "Enum value for identifier: %s does not match: %s != %s" - % (identifier, class_value, value), + f"Enum value for identifier: {identifier} does not match: {class_value} != {value}", ) @classmethod diff --git a/python/resdata/util/test/lint_test_case.py b/python/resdata/util/test/lint_test_case.py index f743fcde1..6092465fd 100644 --- a/python/resdata/util/test/lint_test_case.py +++ b/python/resdata/util/test/lint_test_case.py @@ -43,5 +43,5 @@ def assertLinted(self, paths, whitelist=()): # noqa files = self._get_lintable_files(paths, whitelist=whitelist) for f in files: self.assertEqual( - 0, lint.lint(f, self.LINT_ARGS), "Linting required for %s" % f + 0, lint.lint(f, self.LINT_ARGS), f"Linting required for {f}" ) diff --git a/python/resdata/util/test/path_context.py b/python/resdata/util/test/path_context.py index 5d622265b..2775ace2f 100644 --- a/python/resdata/util/test/path_context.py +++ b/python/resdata/util/test/path_context.py @@ -2,7 +2,7 @@ import shutil -class PathContext(object): +class PathContext: def __init__(self, path, store=False): self.path = path self.cwd = os.getcwd() @@ -24,7 +24,7 @@ def __init__(self, path, store=False): os.makedirs(path) elif not self.store: - raise OSError("Entry %s already exists" % path) + raise OSError(f"Entry {path} already exists") os.chdir(path) def __exit__(self, exc_type, exc_val, exc_tb): diff --git a/python/resdata/util/test/resdata_test_runner.py b/python/resdata/util/test/resdata_test_runner.py index 6a07eb616..bc47bd212 100644 --- a/python/resdata/util/test/resdata_test_runner.py +++ b/python/resdata/util/test/resdata_test_runner.py @@ -3,7 +3,7 @@ from unittest import TestLoader, TextTestRunner -class ResdataTestRunner(object): +class ResdataTestRunner: @staticmethod def runTestSuite(tests, test_verbosity=3): test_runner = TextTestRunner(verbosity=test_verbosity) @@ -47,7 +47,7 @@ def importClass(classpath): m = __import__(classpath[0:dot], globals(), locals(), [class_name]) return getattr(m, class_name) except ImportError: - print("Failed to import: %s" % classpath) + print(f"Failed to import: {classpath}") raise @staticmethod diff --git a/python/resdata/util/test/source_enumerator.py b/python/resdata/util/test/source_enumerator.py index aca52b04a..5953a769a 100644 --- a/python/resdata/util/test/source_enumerator.py +++ b/python/resdata/util/test/source_enumerator.py @@ -2,7 +2,7 @@ import re -class SourceEnumerator(object): +class SourceEnumerator: @classmethod def removeComments(cls, code_string): code_string = re.sub( @@ -15,7 +15,7 @@ def removeComments(cls, code_string): @classmethod def findEnum(cls, enum_name, full_source_file_path): - with open(full_source_file_path, "r") as f: + with open(full_source_file_path) as f: text = f.read() text = SourceEnumerator.removeComments(text) @@ -26,7 +26,7 @@ def findEnum(cls, enum_name, full_source_file_path): if enum[1] == enum_name: return enum[0] - raise ValueError("Enum with name: '%s' not found!" % enum_name) + raise ValueError(f"Enum with name: '{enum_name}' not found!") @classmethod def findEnumerators(cls, enum_name, source_file): diff --git a/python/resdata/util/test/test_area.py b/python/resdata/util/test/test_area.py index 29c75c0c2..9865dccfe 100644 --- a/python/resdata/util/test/test_area.py +++ b/python/resdata/util/test/test_area.py @@ -36,7 +36,7 @@ def __init__(self, test_name, store_area=False, c_ptr=None): if c_ptr is None: c_ptr = self._test_area_alloc(test_name, store_area) - super(TestArea, self).__init__(c_ptr) + super().__init__(c_ptr) def get_original_cwd(self): return self._get_original_cwd() @@ -59,52 +59,52 @@ def install_file(self, filename): if os.path.isfile(self.orgPath(filename)): self._install_file(filename) else: - raise IOError("No such file:%s" % filename) + raise OSError(f"No such file:{filename}") def copy_directory(self, directory): if os.path.isdir(self.orgPath(directory)): self._copy_directory(directory) else: - raise IOError("No such directory: %s" % directory) + raise OSError(f"No such directory: {directory}") def copy_parent_directory(self, path): if os.path.exists(self.orgPath(path)): self._copy_parent_directory(path) else: - raise IOError("No such file or directory: %s" % path) + raise OSError(f"No such file or directory: {path}") def copy_parent_content(self, path): if os.path.exists(self.orgPath(path)): self._copy_parent_content(path) else: - raise IOError("No such file or directory: %s" % path) + raise OSError(f"No such file or directory: {path}") def copy_directory_content(self, directory): if os.path.isdir(self.orgPath(directory)): self._copy_directory_content(directory) else: - raise IOError("No such directory: %s" % directory) + raise OSError(f"No such directory: {directory}") def copy_file(self, filename): if os.path.isfile(self.orgPath(filename)): self._copy_file(filename) else: - raise IOError("No such file:%s" % filename) + raise OSError(f"No such file:{filename}") def free(self): self._free() def getFullPath(self, path): if not os.path.exists(path): - raise IOError("Path not found:%s" % path) + raise OSError(f"Path not found:{path}") if os.path.isabs(path): - raise IOError("Path:%s is already absolute" % path) + raise OSError(f"Path:{path} is already absolute") return os.path.join(self.get_cwd(), path) -class TestAreaContext(object): +class TestAreaContext: __test__ = False def __init__(self, test_name, store_area=False): diff --git a/python/resdata/util/test/test_run.py b/python/resdata/util/test/test_run.py index 6b9955e7c..c5a299926 100644 --- a/python/resdata/util/test/test_run.py +++ b/python/resdata/util/test/test_run.py @@ -7,12 +7,12 @@ def path_exists(path): if os.path.exists(path): - return (True, "Path:%s exists" % path) + return (True, f"Path:{path} exists") else: - return (False, "ERROR: Path:%s does not exist" % path) + return (False, f"ERROR: Path:{path} does not exist") -class TestRun(object): +class TestRun: default_ert_cmd = "ert" default_ert_version = "stable" default_path_prefix = None @@ -37,7 +37,7 @@ def __init__(self, config_file, args=[], name=None): # noqa: B006 break self.name += "/%08d" % random.randint(0, 100000000) else: - raise IOError("No such config file: %s" % config_file) + raise OSError(f"No such config file: {config_file}") def parseArgs(self, args): parser = argparse.ArgumentParser() @@ -95,7 +95,7 @@ def add_check(self, check_func, arg): if callable(check_func): self.check_list.append((check_func, arg)) else: - raise Exception("The checker:%s is not callable" % check_func) + raise Exception(f"The checker:{check_func} is not callable") # ----------------------------------------------------------------- @@ -112,7 +112,7 @@ def __run(self, work_area): if status == 0: return (True, "ert has run successfully") else: - return (False, "ERROR:: ert exited with status code:%s" % status) + return (False, f"ERROR:: ert exited with status code:{status}") def run(self): if len(self.workflows): diff --git a/python/resdata/util/util/__init__.py b/python/resdata/util/util/__init__.py index 0b03cb91c..753cbd851 100644 --- a/python/resdata/util/util/__init__.py +++ b/python/resdata/util/util/__init__.py @@ -21,8 +21,6 @@ """ -from __future__ import absolute_import, division, print_function, unicode_literals - import resdata from cwrap import Prototype @@ -98,9 +96,7 @@ def shift(*args): return args if (method_type != classmethod) else args[1:] def warned_method(*args, **kwargs): - __rd_camel_case_warning( - "Warning, %s is deprecated, use %s" % (camel, str(method_)) - ) + __rd_camel_case_warning(f"Warning, {camel} is deprecated, use {str(method_)}") return method_(*shift(*args), **kwargs) if method_type == staticmethod: diff --git a/python/resdata/util/util/bool_vector.py b/python/resdata/util/util/bool_vector.py index 161ad4a4b..de8fdd270 100644 --- a/python/resdata/util/util/bool_vector.py +++ b/python/resdata/util/util/bool_vector.py @@ -99,7 +99,7 @@ class BoolVector(VectorTemplate): ) def __init__(self, default_value=False, initial_size=0): - super(BoolVector, self).__init__(default_value, initial_size) + super().__init__(default_value, initial_size) def count(self, value=True): """@rtype: int""" diff --git a/python/resdata/util/util/ctime.py b/python/resdata/util/util/ctime.py index 655cd70eb..10116f87d 100644 --- a/python/resdata/util/util/ctime.py +++ b/python/resdata/util/util/ctime.py @@ -33,10 +33,10 @@ def __init__(self, value): value = CTime._timegm(0, 0, 0, value.day, value.month, value.year) else: raise NotImplementedError( - "Can not convert class %s to CTime" % value.__class__ + f"Can not convert class {value.__class__} to CTime" ) - super(CTime, self).__init__(value) + super().__init__(value) def ctime(self): """@rtype: int""" @@ -68,7 +68,7 @@ def __gt__(self, other): elif isinstance(other, (int, datetime.datetime, datetime.date)): return self > CTime(other) else: - raise TypeError("CTime does not support type: %s" % other.__class__) + raise TypeError(f"CTime does not support type: {other.__class__}") def __lt__(self, other): if isinstance(other, CTime): @@ -76,7 +76,7 @@ def __lt__(self, other): elif isinstance(other, (int, datetime.datetime, datetime.date)): return self < CTime(other) else: - raise TypeError("CTime does not support type: %s" % other.__class__) + raise TypeError(f"CTime does not support type: {other.__class__}") def __ne__(self, other): return not self == other @@ -89,7 +89,7 @@ def __eq__(self, other): elif isinstance(other, type(None)): return False else: - raise TypeError("CTime does not support type: %s" % other.__class__) + raise TypeError(f"CTime does not support type: {other.__class__}") def __imul__(self, other): value = int(self.value() * other) diff --git a/python/resdata/util/util/cwd_context.py b/python/resdata/util/util/cwd_context.py index 358f488c9..bc8925bd1 100644 --- a/python/resdata/util/util/cwd_context.py +++ b/python/resdata/util/util/cwd_context.py @@ -1,13 +1,13 @@ import os -class CWDContext(object): +class CWDContext: def __init__(self, path): self.cwd = os.getcwd() if os.path.isdir(path): os.chdir(path) else: - raise IOError("Path:%s does not exist" % path) + raise OSError(f"Path:{path} does not exist") def __exit__(self, exc_type, exc_val, exc_tb): os.chdir(self.cwd) diff --git a/python/resdata/util/util/double_vector.py b/python/resdata/util/util/double_vector.py index f1499fb48..66266c64e 100644 --- a/python/resdata/util/util/double_vector.py +++ b/python/resdata/util/util/double_vector.py @@ -109,4 +109,4 @@ class DoubleVector(VectorTemplate): ) def __init__(self, default_value=0, initial_size=0): - super(DoubleVector, self).__init__(default_value, initial_size) + super().__init__(default_value, initial_size) diff --git a/python/resdata/util/util/hash.py b/python/resdata/util/util/hash.py index 18e8dc13e..153387f9c 100644 --- a/python/resdata/util/util/hash.py +++ b/python/resdata/util/util/hash.py @@ -21,7 +21,7 @@ class Hash(BaseCClass): def __init__(self): c_ptr = self._alloc() - super(Hash, self).__init__(c_ptr) + super().__init__(c_ptr) def __len__(self): return self._size() @@ -30,21 +30,20 @@ def __getitem__(self, key): if self._has_key(key): return self._get(key) else: - raise KeyError("Hash does not have key: %s" % key) + raise KeyError(f"Hash does not have key: {key}") def __setitem__(self, key, value): if isinstance(value, c_void_p): self._insert_ref(key, value) else: - raise ValueError("Hash does not support type: %s" % value.__class__) + raise ValueError(f"Hash does not support type: {value.__class__}") def __contains__(self, key): """@rtype: bool""" return self._has_key(key) def __iter__(self): - for key in self.keys(): - yield key + yield from self.keys() def keys(self): """@rtype: StringList""" @@ -54,7 +53,7 @@ def free(self): self._free() def __str__(self): - return str(["%s: %s" % (key, self[key]) for key in self.keys()]) + return str([f"{key}: {self[key]}" for key in self.keys()]) class StringHash(Hash): @@ -63,19 +62,19 @@ class StringHash(Hash): _insert_string = ResdataPrototype("void hash_insert_string(rd_hash, char*, char*)") def __init__(self): - super(StringHash, self).__init__() + super().__init__() def __setitem__(self, key, value): if isinstance(value, str): self._insert_string(key, value) else: - raise ValueError("StringHash does not support type: %s" % value.__class__) + raise ValueError(f"StringHash does not support type: {value.__class__}") def __getitem__(self, key): if key in self: return self._get_string(key) else: - raise KeyError("Hash does not have key: %s" % key) + raise KeyError(f"Hash does not have key: {key}") class IntegerHash(Hash): @@ -84,19 +83,19 @@ class IntegerHash(Hash): _insert_int = ResdataPrototype("void hash_insert_int(rd_hash, char*, int)") def __init__(self): - super(IntegerHash, self).__init__() + super().__init__() def __setitem__(self, key, value): if isinstance(value, int): self._insert_int(key, value) else: - raise ValueError("IntegerHash does not support type: %s" % value.__class__) + raise ValueError(f"IntegerHash does not support type: {value.__class__}") def __getitem__(self, key): if key in self: return self._get_int(key) else: - raise KeyError("Hash does not have key: %s" % key) + raise KeyError(f"Hash does not have key: {key}") class DoubleHash(Hash): @@ -105,7 +104,7 @@ class DoubleHash(Hash): _insert_double = ResdataPrototype("void hash_insert_double(rd_hash, char*, double)") def __init__(self): - super(DoubleHash, self).__init__() + super().__init__() def __setitem__(self, key, value): if isinstance(value, int): @@ -114,10 +113,10 @@ def __setitem__(self, key, value): if isinstance(value, float): self._insert_double(key, value) else: - raise ValueError("DoubleHash does not support type: %s" % value.__class__) + raise ValueError(f"DoubleHash does not support type: {value.__class__}") def __getitem__(self, key): if key in self: return self._get_double(key) else: - raise KeyError("Hash does not have key: %s" % key) + raise KeyError(f"Hash does not have key: {key}") diff --git a/python/resdata/util/util/int_vector.py b/python/resdata/util/util/int_vector.py index 09208614c..fd0931d37 100644 --- a/python/resdata/util/util/int_vector.py +++ b/python/resdata/util/util/int_vector.py @@ -95,7 +95,7 @@ class IntVector(VectorTemplate): ) def __init__(self, default_value=0, initial_size=0): - super(IntVector, self).__init__(default_value, initial_size) + super().__init__(default_value, initial_size) @classmethod def active_list(cls, range_string): diff --git a/python/resdata/util/util/lookup_table.py b/python/resdata/util/util/lookup_table.py index 45fcb4657..178ac5197 100644 --- a/python/resdata/util/util/lookup_table.py +++ b/python/resdata/util/util/lookup_table.py @@ -30,7 +30,7 @@ class LookupTable(BaseCClass): ) def __init__(self, lower_limit=None, upper_limit=None): - super(LookupTable, self).__init__(self._alloc()) + super().__init__(self._alloc()) if not lower_limit is None: self.setLowerLimit(lower_limit) @@ -99,13 +99,11 @@ def interp(self, x): if x < self.getMinArg(): if not self.hasLowerLimit(): raise ValueError( - "Interpolate argument:%g is outside valid interval: [%g,%g]" - % (x, self.getMinArg(), self.getMaxArg()) + f"Interpolate argument:{x:g} is outside valid interval: [{self.getMinArg():g},{self.getMaxArg():g}]" ) elif x > self.getMaxArg() and not self.hasUpperLimit(): raise ValueError( - "Interpolate argument:%g is outside valid interval: [%g,%g]" - % (x, self.getMinArg(), self.getMaxArg()) + f"Interpolate argument:{x:g} is outside valid interval: [{self.getMinArg():g},{self.getMaxArg():g}]" ) return self._interp(x) diff --git a/python/resdata/util/util/rng.py b/python/resdata/util/util/rng.py index 17274159a..635c54597 100644 --- a/python/resdata/util/util/rng.py +++ b/python/resdata/util/util/rng.py @@ -28,7 +28,7 @@ def __init__( assert isinstance(init_mode, RngInitModeEnum) c_ptr = self._rng_alloc(alg_type, init_mode) - super(RandomNumberGenerator, self).__init__(c_ptr) + super().__init__(c_ptr) def stateSize(self): return self._state_size() @@ -65,7 +65,7 @@ def loadState(self, seed_file): if os.path.isfile(seed_file): self._load_state(seed_file) else: - raise IOError("No such file: %s" % seed_file) + raise OSError(f"No such file: {seed_file}") def saveState(self, seed_file): """ diff --git a/python/resdata/util/util/stringlist.py b/python/resdata/util/util/stringlist.py index 8cd6b2f55..38cf8810e 100644 --- a/python/resdata/util/util/stringlist.py +++ b/python/resdata/util/util/stringlist.py @@ -61,16 +61,14 @@ def __init__(self, initial=None): """ c_ptr = self._alloc() - super(StringList, self).__init__(c_ptr) + super().__init__(c_ptr) if not initial: return if isinstance(initial, str): raise TypeError( - ( - 'Cannot initialize a StringList from "{initial}".\n' - 'Did you mean "[{initial}]"?' - ).format(initial=initial) + f'Cannot initialize a StringList from "{initial}".\n' + f'Did you mean "[{initial}]"?' ) for s in initial: if isinstance(s, bytes): @@ -78,7 +76,7 @@ def __init__(self, initial=None): if isinstance(s, str): self.append(s) else: - raise TypeError('Item is not a string: "%s".' % s) + raise TypeError(f'Item is not a string: "{s}".') def __eq__(self, other): if len(self) == len(other): @@ -110,7 +108,7 @@ def __setitem__(self, index, value): if isinstance(value, str): self._iset(index, value) else: - raise TypeError("Item: %s not string type" % value) + raise TypeError(f"Item: {value} not string type") def __getitem__(self, index): """ @@ -192,9 +190,9 @@ def __str__(self): length = len(self) for i in range(length): if i == length - 1: - buffer += "'%s'" % self[i] + buffer += f"'{self[i]}'" else: - buffer += "'%s'," % self[i] + buffer += f"'{self[i]}'," buffer += "]" return buffer @@ -272,7 +270,7 @@ def index(self, value): if isinstance(value, str): return self._find_first(value) raise KeyError( - 'Cannot index by "%s", lst.index() needs a string.' % str(type(value)) + f'Cannot index by "{str(type(value))}", lst.index() needs a string.' ) def free(self): diff --git a/python/resdata/util/util/thread_pool.py b/python/resdata/util/util/thread_pool.py index bbfd3f6bc..7c45ad548 100644 --- a/python/resdata/util/util/thread_pool.py +++ b/python/resdata/util/util/thread_pool.py @@ -6,7 +6,7 @@ class Task(Thread): def __init__(self, func, *args, **kwargs): - super(Task, self).__init__() + super().__init__() self.__func = func self.__args = args self.__kwargs = kwargs @@ -34,7 +34,7 @@ def run(self): if self.__verbose: running_time = time.time() - self.__start_time - print("Running time of task: %f" % running_time) + print(f"Running time of task: {running_time:f}") def isDone(self): return self.__done @@ -53,9 +53,9 @@ def join(self, timeout=None): time.sleep(0.01) -class ThreadPool(object): +class ThreadPool: def __init__(self, size=None, verbose=False): - super(ThreadPool, self).__init__() + super().__init__() if size is None: size = multiprocessing.cpu_count() diff --git a/python/resdata/util/util/time_vector.py b/python/resdata/util/util/time_vector.py index 0839a7596..effa480e8 100644 --- a/python/resdata/util/util/time_vector.py +++ b/python/resdata/util/util/time_vector.py @@ -116,7 +116,7 @@ class TimeVector(VectorTemplate): def __init__(self, default_value=None, initial_size=0): if default_value is None: - super(TimeVector, self).__init__(CTime(0), initial_size) + super().__init__(CTime(0), initial_size) else: try: default = CTime(default_value) @@ -125,7 +125,7 @@ def __init__(self, default_value=None, initial_size=0): "default value invalid - must be type ctime() or date/datetime" ) from err - super(TimeVector, self).__init__(default, initial_size) + super().__init__(default, initial_size) @classmethod def parseTimeUnit(cls, deltaString): @@ -150,7 +150,7 @@ def __str__(self): """ string_list = [] for d in self: - string_list.append("%s" % d) + string_list.append(f"{d}") return str(string_list) diff --git a/python/resdata/util/util/vector_template.py b/python/resdata/util/util/vector_template.py index d42db20f3..07e1e2a29 100644 --- a/python/resdata/util/util/vector_template.py +++ b/python/resdata/util/util/vector_template.py @@ -25,8 +25,6 @@ float and size_t not currently implemented in the Python version. """ -from __future__ import absolute_import, division, print_function, unicode_literals - import sys from cwrap import CFILE, BaseCClass @@ -126,7 +124,7 @@ def __init__(self, default_value=0, initial_size=0): Creates a new TVector instance. """ c_pointer = self._alloc(initial_size, default_value) - super(VectorTemplate, self).__init__(c_pointer) + super().__init__(c_pointer) self.element_size = self._element_size() def __contains__(self, value): @@ -268,7 +266,7 @@ def __IADD(self, delta, add): delta *= -1 self._shift(delta) else: - raise TypeError("delta has wrong type:%s " % type(delta)) + raise TypeError(f"delta has wrong type:{type(delta)} ") return self @@ -337,7 +335,7 @@ def __imul__(self, factor): elif isinstance(factor, (int, float)): self._scale(factor) else: - raise TypeError("factor has wrong type:%s " % type(factor)) + raise TypeError(f"factor has wrong type:{type(factor)} ") return self @@ -355,7 +353,7 @@ def __div__(self, divisor): copy._div(divisor) return copy else: - raise TypeError("Divisor has wrong type:%s" % type(divisor)) + raise TypeError(f"Divisor has wrong type:{type(divisor)}") def __truediv__(self, divisor): return self.__div__(divisor) diff --git a/python/resdata/util/util/version.py b/python/resdata/util/util/version.py index 5482ee93d..523370c69 100644 --- a/python/resdata/util/util/version.py +++ b/python/resdata/util/util/version.py @@ -14,7 +14,7 @@ def cmp_wrapper(self, other): return cmp_wrapper -class Version(object): +class Version: def __init__(self, major, minor, micro, git_commit=None, build_time=None): self.major = major self.minor = minor @@ -113,6 +113,4 @@ def __init__(self): micro = self._micro_version() git_commit = self._git_commit() build_time = self._build_time() - super(ResdataVersion, self).__init__( - major, minor, micro, git_commit, build_time - ) + super().__init__(major, minor, micro, git_commit, build_time) diff --git a/python/resdata/well/well_connection.py b/python/resdata/well/well_connection.py index 005f07ea5..1f7953325 100644 --- a/python/resdata/well/well_connection.py +++ b/python/resdata/well/well_connection.py @@ -96,20 +96,7 @@ def __repr__(self): msw = " (multi segment)" if self.isMultiSegmentWell() else "" dir = WellConnectionDirection(self.direction()) addr = self._address() - return ( - "WellConnection(%s %s%s%s, rates = (O:%s,G:%s,W:%s), direction = %s) at 0x%x" - % ( - ijk, - frac, - open_, - msw, - self.oilRate(), - self.gasRate(), - self.waterRate(), - dir, - addr, - ) - ) + return f"WellConnection({ijk} {frac}{open_}{msw}, rates = (O:{self.oilRate()},G:{self.gasRate()},W:{self.waterRate()}), direction = {dir}) at 0x{addr:x}" def gasRate(self): return self._gas_rate() diff --git a/python/resdata/well/well_info.py b/python/resdata/well/well_info.py index d86e9e4f3..fa3b14999 100644 --- a/python/resdata/well/well_info.py +++ b/python/resdata/well/well_info.py @@ -32,9 +32,9 @@ def __init__(self, grid, rst_file=None, load_segment_information=True): @type rst_file: str or ResdataFile or list of str or list of ResdataFile """ c_ptr = self._alloc(grid) - super(WellInfo, self).__init__(c_ptr) + super().__init__(c_ptr) if not c_ptr: - raise ValueError("Unable to construct WellInfo from grid %s." % str(grid)) + raise ValueError(f"Unable to construct WellInfo from grid {str(grid)}.") if rst_file is not None: if isinstance(rst_file, list): @@ -58,7 +58,7 @@ def __getitem__(self, item): if isinstance(item, str): if not item in self: - raise KeyError("The well '%s' is not in this set." % item) + raise KeyError(f"The well '{item}' is not in this set.") well_name = item elif isinstance(item, int): @@ -91,7 +91,7 @@ def __contains__(self, item): def _assert_file_exists(self, rst_file): if not isfile(rst_file): - raise IOError("No such file %s" % rst_file) + raise OSError(f"No such file {rst_file}") def addWellFile(self, rst_file, load_segment_information): """@type rstfile: str or ResdataFile""" diff --git a/python/resdata/well/well_segment.py b/python/resdata/well/well_segment.py index 7c4b7e684..ac406f0d3 100644 --- a/python/resdata/well/well_segment.py +++ b/python/resdata/well/well_segment.py @@ -28,7 +28,7 @@ def free(self): pass def __repr__(self): - return "WellSegment(%s) at 0x%x" % (str(self), self._address()) + return f"WellSegment({str(self)}) at 0x{self._address():x}" def __str__(self): return "{Segment ID:%d BranchID:%d Length:%g}" % ( diff --git a/python/resdata/well/well_state.py b/python/resdata/well/well_state.py index cb10dfffa..5cd9d5489 100644 --- a/python/resdata/well/well_state.py +++ b/python/resdata/well/well_state.py @@ -163,18 +163,12 @@ def hasSegmentData(self): def __repr__(self): name = self.name() - name = "%s" % name if name else "[no name]" + name = f"{name}" if name else "[no name]" msw = " (multi segment)" if self.isMultiSegmentWell() else "" wn = str(self.wellNumber()) type_ = self.wellType() open_ = "open" if self.isOpen() else "shut" - cnt = '%s%s, number = %s, type = "%s", state = %s' % ( - name, - msw, - wn, - type_, - open_, - ) + cnt = f'{name}{msw}, number = {wn}, type = "{type_}", state = {open_}' return self._create_repr(cnt) def gasRate(self): diff --git a/python/tests/rd_tests/create_restart.py b/python/tests/rd_tests/create_restart.py index a01ddcdd5..f43121936 100644 --- a/python/tests/rd_tests/create_restart.py +++ b/python/tests/rd_tests/create_restart.py @@ -3,7 +3,7 @@ def create_restart(grid, case, p1, p2=None, rporv1=None, rporv2=None): - with openFortIO("%s.UNRST" % case, mode=FortIO.WRITE_MODE) as f: + with openFortIO(f"{case}.UNRST", mode=FortIO.WRITE_MODE) as f: seq_hdr = ResdataKW("SEQNUM", 1, ResDataType.RD_INT) seq_hdr[0] = 10 p = ResdataKW("PRESSURE", grid.getNumActive(), ResDataType.RD_FLOAT) diff --git a/python/tests/rd_tests/test_fk_user_data.py b/python/tests/rd_tests/test_fk_user_data.py index f468cc71d..90075845f 100644 --- a/python/tests/rd_tests/test_fk_user_data.py +++ b/python/tests/rd_tests/test_fk_user_data.py @@ -16,7 +16,7 @@ def test_cell_containment(self): grid = Grid(grid_file) # Load well data - with open(well_file, "r") as f: + with open(well_file) as f: lines = [line.split() for line in f.readlines()] points = [map(float, line[:3:]) for line in lines] diff --git a/python/tests/rd_tests/test_geertsma.py b/python/tests/rd_tests/test_geertsma.py index de8864998..6a8091625 100644 --- a/python/tests/rd_tests/test_geertsma.py +++ b/python/tests/rd_tests/test_geertsma.py @@ -19,7 +19,7 @@ def create_init(grid, case): for g in range(grid.getGlobalSize()): porv[g] *= grid.cell_volume(global_index=g) - with openFortIO("%s.INIT" % case, mode=FortIO.WRITE_MODE) as f: + with openFortIO(f"{case}.INIT", mode=FortIO.WRITE_MODE) as f: poro.fwrite(f) porv.fwrite(f) diff --git a/python/tests/rd_tests/test_grid.py b/python/tests/rd_tests/test_grid.py index 09529f5bb..4401169c6 100644 --- a/python/tests/rd_tests/test_grid.py +++ b/python/tests/rd_tests/test_grid.py @@ -316,15 +316,15 @@ def test_repr_and_name(self): pfx = "Grid(" rep = repr(grid) self.assertEqual(pfx, rep[: len(pfx)]) - self.assertEqual(type(rep), type("")) - self.assertEqual(type(grid.getName()), type("")) + self.assertEqual(type(rep), str) + self.assertEqual(type(grid.getName()), str) with TestAreaContext("python/rd_grid/repr"): grid.save_EGRID("CASE.EGRID") g2 = Grid("CASE.EGRID") r2 = repr(g2) self.assertEqual(pfx, r2[: len(pfx)]) - self.assertEqual(type(r2), type("")) - self.assertEqual(type(g2.getName()), type("")) + self.assertEqual(type(r2), str) + self.assertEqual(type(g2.getName()), str) def test_node_pos(self): grid = GridGen.createRectangular((10, 20, 30), (1, 1, 1)) diff --git a/python/tests/rd_tests/test_grid_generator.py b/python/tests/rd_tests/test_grid_generator.py index 0b2adcc32..64a1f8262 100644 --- a/python/tests/rd_tests/test_grid_generator.py +++ b/python/tests/rd_tests/test_grid_generator.py @@ -253,6 +253,6 @@ def test_subgrid_translation(self): gc, sc, msg="Failed to translate corners correctly." - + "Expected %s, was %s." % (gc, sc), + + f"Expected {gc}, was {sc}.", tolerance=10e-10, ) diff --git a/python/tests/rd_tests/test_npv.py b/python/tests/rd_tests/test_npv.py index 353f988c6..fcec50641 100644 --- a/python/tests/rd_tests/test_npv.py +++ b/python/tests/rd_tests/test_npv.py @@ -13,7 +13,7 @@ base = "ECLIPSE" path = "Equinor/ECLIPSE/Gurbat" -case = "%s/%s" % (path, base) +case = f"{path}/{base}" def callable(x): diff --git a/python/tests/rd_tests/test_rd_kw.py b/python/tests/rd_tests/test_rd_kw.py index 58f321a15..1338d3bfc 100644 --- a/python/tests/rd_tests/test_rd_kw.py +++ b/python/tests/rd_tests/test_rd_kw.py @@ -182,7 +182,7 @@ def test_fprintf_data(self): kw.fprintf_data(fileH) fileH.close() - with open("test", "r") as fileH: + with open("test") as fileH: data = [] for line in fileH.readlines(): tmp = line.split() diff --git a/python/tests/rd_tests/test_region_equinor.py b/python/tests/rd_tests/test_region_equinor.py index 2f58afd38..b4d03f371 100755 --- a/python/tests/rd_tests/test_region_equinor.py +++ b/python/tests/rd_tests/test_region_equinor.py @@ -10,8 +10,8 @@ class RegionTest(ResdataTest): def setUp(self): case = self.createTestPath("Equinor/ECLIPSE/Gurbat/ECLIPSE") self.grid = Grid(case) - self.rst_file = ResdataFile("%s.UNRST" % case) - self.init_file = ResdataFile("%s.INIT" % case) + self.rst_file = ResdataFile(f"{case}.UNRST") + self.init_file = ResdataFile(f"{case}.INIT") def test_kw_imul(self): P = self.rst_file["PRESSURE"][5] @@ -146,10 +146,10 @@ def test_polygon(self): def test_heidrun(self): root = self.createTestPath("Equinor/ECLIPSE/Heidrun") - grid = Grid("%s/FF12_2013B2_AMAP_AOP-J15_NO62_MOVEX.EGRID" % root) + grid = Grid(f"{root}/FF12_2013B2_AMAP_AOP-J15_NO62_MOVEX.EGRID") polygon = [] - with open("%s/polygon.ply" % root) as fileH: + with open(f"{root}/polygon.ply") as fileH: for line in fileH.readlines(): tmp = line.split() polygon.append((float(tmp[0]), float(tmp[1]))) diff --git a/python/tests/rd_tests/test_rft_equinor.py b/python/tests/rd_tests/test_rft_equinor.py index ef76a3738..af3f7e865 100644 --- a/python/tests/rd_tests/test_rft_equinor.py +++ b/python/tests/rd_tests/test_rft_equinor.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -from __future__ import print_function import datetime from resdata.rft import ResdataRFTFile, ResdataRFTCell, ResdataPLTCell, WellTrajectory from tests import ResdataTest, equinor_test diff --git a/python/tests/rd_tests/test_sum_equinor.py b/python/tests/rd_tests/test_sum_equinor.py index fb0f900ff..9c6422482 100755 --- a/python/tests/rd_tests/test_sum_equinor.py +++ b/python/tests/rd_tests/test_sum_equinor.py @@ -13,7 +13,7 @@ base = "ECLIPSE" path = "Equinor/ECLIPSE/Gurbat" -case = "%s/%s" % (path, base) +case = f"{path}/{base}" def sum_get(*args): diff --git a/python/tests/util_tests/test_work_area.py b/python/tests/util_tests/test_work_area.py index 625853520..151435aa5 100644 --- a/python/tests/util_tests/test_work_area.py +++ b/python/tests/util_tests/test_work_area.py @@ -55,9 +55,7 @@ def test_multiple_areas(self): self.assertEqual( loop_dir, original_dir, - "Wrong folder before creating TestAreaContext. Loop: {} -- CWD: {} ".format( - i, loop_dir - ), + f"Wrong folder before creating TestAreaContext. Loop: {i} -- CWD: {loop_dir} ", ) with TestAreaContext("test_multiple_areas") as t: @@ -66,9 +64,7 @@ def test_multiple_areas(self): self.assertNotIn( t_dir, context_dirs, - "Multiple TestAreaContext objects in the same folder. Loop {} -- CWD: {}".format( - i, loop_dir - ), + f"Multiple TestAreaContext objects in the same folder. Loop {i} -- CWD: {loop_dir}", ) context_dirs.append(t_dir) @@ -77,18 +73,14 @@ def test_multiple_areas(self): self.assertNotEqual( t_dir, original_dir, - "TestAreaContext in the current working directory. Loop: {} -- CWD: {}".format( - i, loop_dir - ), + f"TestAreaContext in the current working directory. Loop: {i} -- CWD: {loop_dir}", ) loop_dir = os.getcwd() self.assertEqual( loop_dir, original_dir, - "Wrong folder after creating TestAreaContext. Loop: {} -- CWD: {} ".format( - i, loop_dir - ), + f"Wrong folder after creating TestAreaContext. Loop: {i} -- CWD: {loop_dir} ", )