rspec/rules/S2824/python/rule.adoc

34 lines
932 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!
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
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
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
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[]