Details
-
Type:
RFC
-
Status: Implemented
-
Resolution: Done
-
Component/s: DM
-
Labels:None
Description
In Python PropertySet.get(name) will return a scalar if there is only one element, and an array if there is more than one element. Similarly for PropertyList. I think this encourages unsafe code. When expecting a scalar it is far too easy to expect there will only be one element and not check. Similarly, when expecting an array, one may be surprised to get a scalar if the array happens to only have one element.
I suggest we add two methods to PropertySet and PropertyList in Python:
- getScalar(name): return the last value of the array, like C++ get<T>
- getArray(name): return the data as an array, even if it only has one element. This is like C++ getArray<T>.
I further suggest that we deprecate get and use these new methods for all new code. It avoids obvious bugs and makes the intent clearer. Here are some before and after examples:
scalar = metadata.get("ascalar") # unsafe; breaks if more than one value
|
scalar = metadata.get("ascalar", asArray=True)[-1] # safe and clear but ugly
|
scalar = metadata.get("ascalar", True)[-1] # safe but unclear
|
scalar = metadata.getScalar("ascalar")
|
|
array = metadata.get("anarray") # unsafe; breaks if only one value
|
array = metadata.get("anarray", asArray=True) # safe and clear
|
array = metadata.get("anarray", True) # safe but unclear
|
array = metadata.getArray("anarray")
|
Note that the safe old style examples use the flag asArray. This is an optional argument to get that I didn't know existed until today. It is undocumented. I'm curious how many folks even knew about it, and are confident they know what it does.
Other than a few comments in Slack I've seen no discussion. Robert Lupton said something about FITS that I can't find right now.
I did not not intended this RFC to be about FITS. I proposed it for two main reasons:
One issue is what getScalar should do if there is more than one value. This RFC proposes to silently return the last value, just like C++ get<type> ("most recent wins"). Another option would be to raise an exception. I prefer the former but am open to the latter, or having a doRaise argument, if others feel strongly enough about it.