带有默认值的参数修改¶
ID: py/modification-of-default-value
Kind: path-problem
Security severity:
Severity: error
Precision: high
Tags:
- reliability
- maintainability
Query suites:
- python-security-and-quality.qls
参数的默认值在创建函数时计算一次,而不是在每次调用时计算。然后,“预计算”的值用于随后对函数的每次调用。因此,如果您修改了参数的默认值,则此“修改后的”默认值将在未来对函数的调用中用于该参数。这意味着函数在未来的调用中可能无法按预期工作,并且还会使函数更难理解。
建议¶
如果参数具有默认值,请不要修改默认值。当您将可变对象用作默认值时,您应该使用占位符值而不是修改默认值。当您使用列表和字典时,这是一个特别的问题,但是存在避免修改默认参数的标准方法(请参阅参考资料)。
示例¶
在以下示例中,default
参数设置为一个空列表的默认值。函数中的其他命令随后将值追加到列表中。下次调用该函数时,列表将包含值,这可能不是预期的。
def __init__(self, name, choices=[], default=[], shortDesc=None,
longDesc=None, hints=None, allowNone=1): # 'default' parameter assigned a value
self.choices = choices
if choices and not default:
default.append(choices[0][1]) # value of 'default' parameter modified
Argument.__init__(self, name, default, shortDesc, longDesc, hints, allowNone=allowNone)
建议的解决方法是使用占位符值。也就是说,用 default=None
定义函数,检查参数是否为 None
,然后将参数设置为列表。
参考资料¶
Effbot: Python 中的默认参数值。
Python 语言参考:函数定义。