I've found the following code invaluable in helping me 'handle' None values including "whitespace" characters that should be treated as None based on the situation. I have been using this code for quite some time now:
class _MyUtils:
def __init__(self):
pass
def _mynull(self, myval, myalt, mystrip=True, mynullstrings=["", "None"], mynuminstances=(int, float)):
# if the value is None, return the alternative immediately.
if myval is None:
return myalt
# if the value is a number, it is not None - so return the original
elif isinstance(myval, mynuminstances):
return myval
# if the mystrip parameter is true, strip the original and test that
else:
if mystrip:
testval = myval.strip()
else:
testval = myval
# if mynullstrings are populated, check if the upper case of the
# original value matches the upper case of any item in the list.
# return the alternative if so.
if len(mynullstrings) > 0:
i = 0
for ns in mynullstrings:
if ns.upper() == testval.upper():
i = i + 1
break
if i > 0:
return myalt
else:
return myval
else:
return myval
def main():
x = _MyUtils()
print(x._mynull(None, "alternative_value", True, [""]))
if __name__ == '__main__':
main()
The code requires an input, an alternative to provide if input is found to be Null, whether to 'strip' the input during testing (if not a number), values to treat as 'equivalent' to None and types of number instances to determine if the input is numeric (and hence not none).
Essentially, too many processes that we run depend upon not having None values in the data being processed—whether that be lambda functions, custom table toolsets, etc. This code gives me the ability to handle None values predictably, but I am sure there is a better approach here. Is there a more Pythonic way of doing this? How can this code be improved? How would others approach this problem?