All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S5717.html Maven / Gradle / Ivy

There is a newer version: 4.23.0.17664
Show newest version

This rule raises an issue when the default value of a function parameter is mutated.

Why is this an issue?

In Python, function parameters can have default values.

These default values are expressions which are evalutated when the function is defined, i.e. only once. The same default value will be used every time the function is called. Therefore, modifying it will have an effect on every subsequent call. This can lead to confusing bugs.

def myfunction(param=foo()):  # foo is called only once, when the function is defined.
    ...

For the same reason, it is also a bad idea to store mutable default values in another object (ex: as an attribute). Multiple instances will then share the same value and modifying one object will modify all of them.

This rule raises an issue when:

  • a default value is either modified in the function or assigned to anything other than a variable and it has one of the following types:
    • collections module: deque, UserList, ChainMap, Counter, OrderedDict, defaultdict, UserDict.
  • an attribute of a default value is assigned.

Exceptions

In some rare cases, modifying a default value is intentional. For example, default values can be used as a cache.

No issue will be raised when the parameter’s name contains "cache" or "memo" (as in memoization).

How to fix it

When a parameter default value is meant to be a mutable object, it is best to keep the parameter optional and instantiate the mutable object in the function’s body directly.

Code examples

Noncompliant code example

In the following example, the parameter "param" has list() as a default value. This list is created only once and then reused in every call. Thus when appending 'a' to this list in the body of the function, the next call will have ['a'] as a default value.

def myfunction(param=list()):  # Noncompliant: param is a list that gets mutated
    param.append('a')  # modification of the default value.
    return param

print(myfunction()) # returns ['a']
print(myfunction()) # returns ['a', 'a']
print(myfunction()) # returns ['a', 'a', 'a']

Compliant solution

def myfunction(param=None):
    if param is None:
        param = list()
    param.append('a')
    return param

print(myfunction()) # returns ['a']
print(myfunction()) # returns ['a']
print(myfunction()) # returns ['a']

Resources

Documentation

External coding guidelines





© 2015 - 2024 Weber Informatics LLC | Privacy Policy