Returning a private array directly

Returning a private array directly

Description

Returning an internal list or array directly gives the caller a reference it can use to change the object’s state.

Potential impact

Callers can alter permission or policy lists outside the checks enforced by the object.

Remediation

Return a Python list copy using a slice, list() or the list’s copy() method. Return a tuple if callers need no editable sequence. Both shallow copies and tuples still share mutable elements, so protect those separately when needed. For independent NumPy array storage, use copy() because basic slices are views.

Examples

The example assumes a Python list whose elements need no separate copy.

Before

python
def get_values(self):
    return self.__values

After

python
def get_values(self):
    return self.__values[:]

Returning self.__values[:] lets the caller add, remove or replace entries in its copy without changing the entries in the internal list.

References