I am wondering about the most pythonic way to implement a function that can act in different modes, i.e. perform a slightly different task depending on which mode it is called in.
For example, I have the following to extract a subset of a numpy array based on a set of input indices. Typically I will want to pass in these indices as a list or tuple of the form [xMin, xMax, yMin, yMax]
, however I may sometimes want to provide a centerpoint and a width/height, as ([xCoord, yCoord], [width, height])
. (Note that this is spatial data & xMin
, yMin
etc. refer to the spatial coordinates of the array bounds.)
def get_subset(array, *args):
## If window extents are given
if len(args) == 1:
[(xMin,xMax,yMin,yMax)] = args
## Set NULL extents to array bounds
if xMin is None: xMin = array.xMin
if xMax is None: xMax = array.xMax
if yMin is None: yMin = array.yMin
if yMax is None: yMax = array.yMax
## Convert window extents to array indices
winLx = int(xMin - array.xMin)
winRx = int(xMax - array.xMin)
winBy = int(array.yMax - yMin)
winTy = int(array.yMax - yMax)
## If window centroid and dimensions are given
elif len(args) == 2:
[(easting,northing),(width,height)] = args
# Convert input coordinates into array indices
xCell = int(easting - array.xMin)
yCell = int(array.yMax - northing)
# Generate L(eft), R(ight), T(op) and B(ottom) window extents
winLx = xCell - width//2
winRx = xCell + width//2
winBy = yCell + height//2
winTy = yCell - height//2
subset = array.data[winTy:winBy, winLx:winRx, :]
Is there a better, more concise or more pythonic way to do this? In the past I have tried using a mode
argument to my function and then using if
loops to get the functionality I want (something like get_subset(array, window, mode='extent')
), which ends up being not so different from what I have shown above. However I wonder if there is a nice way to use decorators or some other python functionality to accomplish this.