rspec/rules/S2824/python/rule.adoc
2022-02-04 16:28:24 +00:00

34 lines
932 B
Plaintext

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
[source,python]
----
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
[source,python]
----
def get_attr_array(obj, arr):
props = (name for name in dir(obj) if not name.startswith('_'))
arr.extend(props)
return arr
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]