-
-
Notifications
You must be signed in to change notification settings - Fork 416
Description
Is your feature request related to a problem?
Running a tool through the new tool API currently always returns a values, specifically an instance of ToolResult. This creates clutter in notebooks, doctest and with other interactive use when a lot of calls of GRASS tools produce data in the GRASS project or files rather than text outputs to show on the screen right away. See for example the g_region and r_random_surface calls below:
>>> import grass.script as gs
>>> from grass.tools import Tools
>>> gs.create_project("xy_project")
>>> session = gs.setup.init("xy_project")
>>> tools = Tools(session=session)
>>> tools.g_region(rows=100, cols=100)
ToolResult(...)
>>> tools.r_random_surface(output="surface", seed=42)
ToolResult(...)Returning None when there is no text would create an expected result for the two calls above while still working in the same way when there is output, for example:
>>> tools.g_region(rows=100, cols=100)
>>> print("cells:", tools.g_region(flags="p", format="json")["cells"])
cells: 10000In case of NumPy outputs proposed in #5878, the returned value will become dynamic, ToolResult by default, but with outputs set to arrays, it will be arrays (technically an array or a tuple of arrays):
>>> import numpy as np
>>> tools.g_region(rows=2, cols=3)
>>> slope = tools.r_slope_aspect(elevation=np.ones((2, 3)), slope=np.ndarray)
>>> tools.r_grow(input=np.array([[1, np.nan, np.nan], [np.nan, np.nan, np.nan]]), radius=1.5, output=np.ndarray)
array([[1., 1., 0.],
[1., 1., 0.]])
>>> (slope, aspect) = tools.r_slope_aspect(
... elevation=np.ones((2, 3)), slope=np.array, aspect=np.array
... )The dynamic return value type in case of NumPy suggests that adding another would fit with the overall idea of returning the expected value (as opposed to returning ToolResult even when there is no text output)
Describe the solution you'd like
Return None when there is not text output, for example:
>>> tools.g_region(rows=100, cols=100)
>>> tools.r_random_surface(output="surface", seed=42)Describe alternatives you've considered
Returning a ToolResult object always, not only with no text output but even with NumPy arrays would create maximum consistency and predictability. However, I think that would not necessary meet the overall expectations and convenience. The consistent behavior can be implemented as an opt-in option, for example:
>>> tools = Tools(session=session, always_result=True)
>>> result = tools.r_slope_aspect(
... elevation=np.ones((2, 3)), slope=np.array, aspect=np.array
... )
>>> slope = result.arrays.slope
>>> aspect = result.arrays.aspect
>>> result.text
''Additional context
- grass.tools: Add NumPy arrays IO to Tools #5878
grass/python/grass/tools/session_tools.py
Line 213 in f16cd65
return self.run_cmd(