Python non None defaults

Programmer A writes the following function:

def compute_value(threshold = sys.float_info.max):
   ...
   return value

which has an optional parameter threshold, which naturally has a maximum float value as the default value for the "no threshold" view.

Programmer B also has a view for the threshold, but uses None to represent the absence of a threshold. Unfortunately, the compute_value function does not throw any exceptions if the threshold is = None, but it gives the wrong answer. Therefore, it is an error when programmer B skips None as a threshold.

I would say that the best solution is to change the function in

def compute_value(threshold = None):
    if threshold is None:
        threshold = sys.float_info.max
    ...
    return value

since this function is more general than before, because it treats the None value in a way that makes sense.

: None ?

, , , None, . None kwargs...

( , ) . B :

def compute_value(threshold = sys.float_info.max):
    if threshold is None:
        threshold = sys.float_info.max
    ...
    return value

, . , sys.float_info.max ... : DRY? , , None, None sys.float_info.max - .

+4
2

, ( API), None . , , sys.float_info.max None. , None float? None - , .

- None, help , None, " ", ( , , ). 1

, , . , . .


1 , (, sphinx) sys.float_info.max , , . . IEEE, ...

+4

None , kwargs

def compute_value(**kwargs):
    threshold = kwargs.get('threshold', sys.float_info.max)
    ...
    return value
+1

Source: https://habr.com/ru/post/1540642/


All Articles