io.common
Module for common IO definitions # @doc
- class gridr.io.common.GridRIOMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Defines input/output (I/O) modes for computations.
This enumeration is used to specify whether a particular operation or data context pertains to input or output.
Members
- INPUTint
Represents an input mode (value = 1).
- OUTPUTint
Represents an output mode (value = 2).
- class gridr.io.common.SafeContext(resource)[source]
A context manager designed to safely wrap another resource, especially useful for optional resources or those whose context manager status is uncertain.
This context manager provides flexible behavior based on the wrapped resource:
If resource is None: * __enter__ will return None. * __exit__ will perform no action.
If resource is a valid context manager (i.e., it implements both __enter__ and __exit__ methods): * SafeContext will delegate to that resource’s __enter__ and __exit__ methods, effectively behaving just like the wrapped resource’s own context manager.
If resource is not None but also not a context manager: * __enter__ will simply return the resource itself. * __exit__ will perform no action.
This class ensures that operations within a with statement are performed safely without errors even if the underlying resource is None or not a proper context manager.
Examples
>>> class MyResource: ... def __init__(self, name): ... self.name = name ... print(f"Resource {self.name} created") ... def close(self): ... print(f"Resource {self.name} closed") >>> >>> # Case 1: Wrapping a context manager (like a file) >>> with SafeContext(open("temp.txt", "w")) as f: ... if f: ... f.write("Hello") ... # File 'temp.txt' is automatically closed here. >>> import os >>> os.remove("temp.txt") >>> >>> # Case 2: Wrapping None >>> with SafeContext(None) as res: ... print(f"Resource inside context: {res}") ... # Output: Resource inside context: None >>> >>> # Case 3: Wrapping a non-context manager object >>> with SafeContext(MyResource("Test")) as res: ... if res: ... print(f"Resource name: {res.name}") ... # Output: Resource Test created ... # Output: Resource name: Test >>> # MyResource.close() is NOT called automatically as it's not a context manager
- gridr.io.common.open_raster_or_none(apath, *args, **kwargs)[source]
Opens a raster file with Rasterio, or returns None if the path is None.
This utility function provides a convenient way to attempt opening a raster file. If apath is None, it directly returns None without attempting to open a file, which is useful for optional inputs. Otherwise, it delegates to rasterio.open().
- Parameters:
apath (str or None) – The path to the raster file to open. If None, the function returns None.
*args (
Any) – Additional positional arguments to pass to rasterio.open().**kwargs (
Any) – Additional keyword arguments to pass to rasterio.open().
- Returns:
A rasterio.io.DatasetReader object if apath is a valid path and the file is successfully opened. Returns None if apath is None.
- Return type:
rasterio.io.DatasetReader or None
- gridr.io.common.safe_raster_open(apath, *args, **kwargs)[source]
Provides a safe context manager for opening raster files, or handling None paths.
This function acts as a convenient alias, streamlining the pattern of using SafeContext with the open_raster_or_none helper. It creates a SafeContext instance, passing it the result of open_raster_or_none. This allows for clean with statements where the resource can be either an opened rasterio dataset or None if the path was None.
- Parameters:
apath (str or None) – The path to the raster file to open. If None, the SafeContext will yield None when entered.
*args (
Any) – Additional positional arguments to pass through to rasterio.open() via open_raster_or_none.**kwargs (
Any) – Additional keyword arguments to pass through to rasterio.open() via open_raster_or_none.
- Returns:
An instance of SafeContext that will manage the safe opening and closing of the raster file (or None handling) within a with statement.
- Return type:
Examples
>>> # Create a dummy raster for the example >>> import os >>> with rasterio.open("example_raster.tif", 'w', driver='GTiff', ... height=1, width=1, count=1, dtype='uint8') as dst: ... dst.write(np.array([[10]], dtype='uint8'), 1) >>> >>> # Using with a valid path >>> with safe_raster_open("example_raster.tif", 'r') as src: ... if src: ... print(f"Raster opened successfully: {src.name}") ... # Perform operations with 'src' ... else: ... print("Raster was not opened.") >>> os.remove("example_raster.tif") # Clean up >>> >>> # Using with a None path >>> with safe_raster_open(None) as src_none: ... if src_none: ... print(f"Raster opened successfully: {src_none.name}") ... else: ... print("Path was None, raster not opened.") >>> >>> # Handling a non-existent file (Rasterio will raise an error) >>> try: ... with safe_raster_open("non_existent_file.tif", 'r') as src_invalid: ... pass ... except rasterio.errors.RasterioIOError as e: ... print(f"Caught expected Rasterio error: {e}")