A scikit-learn estimator's __init__ sets an attribute ending in _, which marks fitted state

tx0/python:estimator-init-sets-fitted-attributerecommendedwarningreliability/collectionsdepth fastbug

What it finds

scikit-learn treats public attributes that end with an underscore, such as coef_, as the result of fit; check_is_fitted looks for them. Setting one in __init__ makes an unfitted estimator look fitted, and clone drops it because it is not a parameter.

From the rule's source, estimator_init_sets_fitted_attribute.rs.

Example from the rule's tests
from sklearn.base import BaseEstimator class Scaler(BaseEstimator):    def __init__(self, factor=1.0):        self.factor = factor        self.mean_ = Nonetx0 reports: an attribute ending in _ set in __init__        self._cache = None     def fit(self, x):        self.mean_ = x.mean()        return self class Plain:    def __init__(self):        self.mean_ = None
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/python:estimator-init-sets-fitted-attribute" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

# tx0: ignore[tx0/python:estimator-init-sets-fitted-attribute] reason="..."

tx0 explain tx0/python:estimator-init-sets-fitted-attribute shows the same in the terminal. Found a false positive? Report it.