Returning a private array directly

Returning a private array directly

Description

If a public method returns an internal private list or array directly, the caller can use the returned reference to change the object's internal state.

Potential impact

  • External code may change permission lists, policy lists or validated values.
  • Object invariants may be bypassed.

Remediation

  • Return a copy of a Python list using slicing, list() or copy(). Basic slicing of a NumPy array creates a view; use the array's copy() method when independent data is required.
  • Expose values as an immutable type such as a tuple when callers do not need to modify them. Shallow copies and tuples still share mutable elements, so check whether those elements also need protection.

Examples

These excerpts assume a Python list whose individual elements do not require separate copies.

Before

python
def get_values(self):
    return self.__values

After

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

Explanation:

  • Before: Returns the internal private list or array directly, allowing the caller to modify internal state through the reference.
  • After: Returns a shallow list copy so additions, removals or element replacement in the returned list do not directly change the internal list.

References