8000 ENH: Add tests for linalg.getattr deprecation mechanism · Issue #29898 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

ENH: Add tests for linalg.getattr deprecation mechanism #29898

@anikchand461

Description

@anikchand461

Enhancement Proposal: Tests for linalg.__getattr__ Deprecation

Description:
The __getattr__ hook in numpy/linalg/linalg.py (around line 10) forwards attributes from the private _linalg module while issuing a DeprecationWarning to guide users to the public API. This is great for backward compatibility, but it currently lacks dedicated tests in numpy/linalg/tests/test_linalg.py for key behaviors like:

  • Successful attribute forwarding (e.g., inv, det) with correct warning emission.
  • Raising AttributeError for missing attributes.
  • Accurate stacklevel=3 in warnings for proper traceback pointing.

Adding these would ensure reliability, especially for ML workflows relying on linalg (e.g., SVD in data augmentation or solving in regression, as in my projects using NumPy with TensorFlow/scikit-learn).

Proposed Changes:

  • Add a new test class TestLinalgGetattrDeprecation with pytest functions:
    • test_getattr_successful: Captures warning and asserts array equality (e.g., for inv on a sample matrix).
    • test_getattr_missing: Asserts AttributeError for non-existent attr like foo.
    • test_getattr_stacklevel: Verifies warning frame points to caller.
  • Use warnings.catch_warnings and numpy.testing.assert_array_equal for assertions.
  • Aim for 100% coverage of the __getattr__ logic.

Minimal Repro/Expected Behavior:
Here's a snippet demonstrating the current behavior (tested on NumPy 2.1.0, Python 3.12):

import numpy as np
import warnings

# Successful access
with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    A = np.array([[1, 2], [3, 4]], dtype=float)
    result = np.linalg.linalg.inv(A)  # Triggers warning
    expected = np.linalg.inv(A)
    # Assert result == expected and warning emitted
print("Warning emitted:", len(w) == 1)
print("Warning message:", str(w[0].message) if w else "No warning")

# Missing attr
try:
    _ = np.linalg.linalg.foo
except AttributeError as e:
    print("Error:", str(e))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0