python类定义默认值为none_python non无默认值(python non None default values)

Programmer A writes the following function:

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

...

return value

which has the optional parameter threshold which in a natural way has the maximum float value as a default to represent "no threshold".

Programmer B has also a representation for a threshold, but uses None to represent the absence of threshold. Unfortunately the compute_value function does not raise any exception if threshold=None but gives the incorrect answer. Hence a bug when programmer B passes None as 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, as it handles the None value in a way which makes sense.

This poses the question: is it always best to use only None as default values?

It is not the first time that functions having default parameters different from None cause trouble to me. In other situations I was finding myself to remove None values from a kwargs dictionary...

Another related (maybe silly) question. Actually programmer B modified the function above as follows:

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

if threshold is None:

threshold = sys.float_info.max

...

return value

which is perfectly correct but seems bad to me. Bad because sys.float_info.max is repeated twice... but: is this a violation of the DRY principle? Because, strictly speaking, also None is repeated twice in the first implementation and both None and sys.float_info.max are constants.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值