This question is more coding style related which is why this question is asked here.
I'm new to Python, coming from PHP. I've been looking through Python style guides & code examples, I've noticed the None data type is used where I wouldn't use it.
I always avoid using the None/Null data type. I always like to keep everything (variable types, param types, property types, return types) in the one data type that they're supposed to be. And so instead of using None, I prefer to have an empty data type (That equates to falsy), so:
For strings: ''
For lists: []
For dicts: {}
For bools: True/False
For ints: 0
if only positive ints expected. -1
if 0 or positive ints are expected. None
if any ints (positive, negative, 0) are expected.
For floats: 0.0
if only positive floats expected, otherwise None
.
With ints, if I use -1 for default params, then -1 is viewed as the empty int (instead of 0) and will be checked explitly using:
if my_var == -1:
#... my_var is empty
Here is an example using None as the defaults:
def my_function(my_string=None, my_list=None, my_number=None, my_bool=None, my_dict=None):
"""Return [1, 2, 3] if all args are truthy, otherwise return None.
- Defaults parameters are all None.
- Could return list or None.
"""
if my_list and my_number and my_string and my_bool and my_dict:
return [1, 2, 3]
else:
return None
This is how I would prefer to write the above by using empty data types:
def my_function(my_string: str = '', my_list: list = [], my_number: int = 0, my_bool: bool = False, my_dict: dict = {}) -> list:
"""Return [1, 2, 3] if all args are truthy, otherwise return empty list.
- Default parameters are empty data types.
- Will always return the one expected data type.
- Because of this we can always use data type hints everything.
"""
if my_list and my_number and my_string and my_bool and my_dict:
return [1, 2, 3]
else:
return []
I hardly ever use the None/Null data type. I would like to hear views about these two coding styles.
for
loop over an empty collection will do nothing. Afor
loop overNone
will crash. When doing nothing is preferred, use empty collections. However, I would avoid things like empty strings,0
/-1
,false
as defaults at all costs.None
throws an error when used.-1
does not. Errors will silently propagate through your system, that could have been detected early ifNone
was used.