Skip to content

MAINT: Add _NoValue sentinel and initialize OLS conditional attributes (GH#9880) - #10024

Closed
ChinesePrince07 wants to merge 1 commit into
statsmodels:mainfrom
ChinesePrince07:novalue-sentinel-linear-model
Closed

ChinesePrince07 wants to merge 1 commit into
statsmodels:mainfrom
ChinesePrince07:novalue-sentinel-linear-model

Conversation

@ChinesePrince07

Copy link
Copy Markdown

First slice of #9880, following the suggestion there to use a _NoValue sentinel rather than None. I kept it to one module so the pattern can be reviewed before sweeping the rest of the codebase.

Infrastructure: statsmodels/tools/_no_value.py defines a _NoValue singleton modelled on numpy._NoValue (numpy/_globals.py): singleton __new__, a reload guard, and __reduce__ so identity survives pickle round-trips under every protocol. Results objects are pickled by save/load, so attr is _NoValue must still hold after loading.

Application (regression.linear_model): OLS now always initializes its conditionally-set attributes - offset and the score/hessian intermediates _wendog_xprod, _wexog_xprod, _wexog_x_wendog - to _NoValue, and the four hasattr probes in loglike, score, hessian and _setup_score_hess become is _NoValue checks. Behavior is unchanged, including OLS(y, x, offset=None), which still attaches None (a passed value, distinguishable from an unset attribute - the distinction the sentinel exists for).

I deliberately left the remaining hasattr/getattr sites in the module, since a sentinel on self cannot fix them:

  • hasattr(model, "wexog_singular_values") in RegressionResults.__init__: model is duck-typed - GLM, GAM and IV2SLS instances also pass through here, so this site needs those modules converted first.
  • the cov_type guards: cov_type is always set by RegressionResults.__init__, but subclasses in sandbox/emplike/quantile construct results in ways I did not want to audit in this PR; removing those guards is a separate cleanup.
  • getattr(restricted, ...) in compare_f_test/compare_lr_test: restricted is a caller-supplied results object.
  • hasattr(self, "resid") in resid_pearson: probes whether a cached property can still be computed after remove_data, not a conditionally-set attribute.
  • hasattr(groups, ...): duck-typing of user input.

Tests: tools/tests/test_no_value.py covers singleton identity, repr and pickle identity under every protocol. Two new tests in regression/tests/test_regression.py cover sentinel initialization, unchanged loglike/score/hessian with and without offset, the offset=None distinction, and a pickle round-trip. pytest statsmodels/regression/ statsmodels/tools/ statsmodels/emplike/ passes locally: 1374 passed, 16 skipped. flake8 is clean on the touched files.

If this shape looks right I will convert the remaining modules (discrete, base, tsa, genmod, ...) in follow-up PRs of similar size.

Add statsmodels.tools._no_value._NoValue, a singleton sentinel modelled
on numpy._NoValue, for marking instance attributes that have not been
set. Unlike None it cannot collide with a legitimate attribute value,
and it preserves identity across pickle round-trips so is-checks hold
on loaded results.

Use it in regression.linear_model: OLS now always initializes offset
and the score/hessian intermediates (_wendog_xprod, _wexog_xprod,
_wexog_x_wendog), replacing the hasattr probes in loglike, score,
hessian and _setup_score_hess with is-_NoValue checks. Behavior is
unchanged.

First module of GH#9880.
@bashtage

bashtage commented Aug 4, 2026

Copy link
Copy Markdown
Member

Not sure about this. None is fine as long as it is the sentinel. The issue for _NoValue occurs when None indicates to do one thing, and a different value something else.

Is there a difference between None and _NoValue here?

@bashtage

bashtage commented Aug 4, 2026

Copy link
Copy Markdown
Member

The point of that thread is that attributes often magically appear in classes, and so there is a lot of hasattr checks to try and figure out things. This is a bad idea. Attributes should always exist and usually be filled with None, so that one can do

if some_attr is not None:  # We know it is used
    do_something_with(some_attr)

@bashtage

bashtage commented Aug 4, 2026

Copy link
Copy Markdown
Member

This fix asked for in that thread is to be model by model and to make sure that attributes are created during __init__ and then None if that can't be filed until later.

This is an important way forward as it will allow for typing. statsmodels in its current approach is impossible to type.

# Disallow reloading this module so as to preserve the identity of _NoValue.
if "_is_loaded" in globals():
raise RuntimeError("Reloading statsmodels.tools._no_value is not allowed")
_is_loaded = True
@bashtage

bashtage commented Aug 7, 2026

Copy link
Copy Markdown
Member

Going to close. We don't need a _NoValue. The intent of the issue referenced is to ensure that attributes are always initialized in init of classes,.possible with None. We can then check for None. If there is a case where None is a permitted value to indicate something, then a _NoValue or _NoDefukatValue can make sense.

I'm still happy to have changes that will make sure attributes always exist in models so that hasattr and getattr are not needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants