rspec/rules/S2824/python/rule.adoc

20 lines
736 B
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
While the assignment of default parameter values is typically a good thing, it can go very wrong very quickly when mutable objects are used. That's because a new instance of the object _is not_ created for each function invocation. Instead, all invocations share the same instance, and the changes made for one caller are made for all!
== Noncompliant Code Example
----
def get_attr_array(obj, arr=[]): # Noncompliant
props = (name for name in dir(obj) if not name.startswith('_'))
arr.extend(props) # after only a few calls, this is a big array!
return arr
----
== Compliant Solution
----
def get_attr_array(obj, arr):
props = (name for name in dir(obj) if not name.startswith('_'))
arr.extend(props)
return arr
----