Why the conditional statement like "if regressor:" causes an error?

Viewed 42

I have tested several kinds of regressors from scikit-learn. But, when I use if-statement only with regressor, I faced the error case like the sample code below.

from sklearn.neural_network import MLPRegressor
from sklearn.ensemble import GradientBoostingRegressor, HistGradientBoostingRegressor

for j, model in enumerate([MLPRegressor(), HistGradientBoostingRegressor(), GradientBoostingRegressor()]):
    if model:
        print(f'{j}: True. You defined the model: %s'%type(model))

0: True. You defined the model: <class 'sklearn.neural_network._multilayer_perceptron.MLPRegressor'>
1: True. You defined the model: <class 'sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor'>
AttributeError: 'GradientBoostingRegressor' object has no attribute 'estimators_'

Unlike the first two models, only the third model causes AttributeError. On the other hand, if model is not None: doesn't cause the error. Why is that?

1 Answers

When evaluating if not <object>, python interpreter checks __nonzero__() dunder method (if implemented), then a non-zero return value of __len__() (if implemented) and finally compares the object to None.

Depending by inheritance, there is some inconsistency regarding __len__() implementation in different sklearn model classes. It is a known issue (see e.g. https://github.com/scikit-learn/scikit-learn/issues/23769, https://github.com/scikit-learn/scikit-learn/issues/10487) yet as far as I know, it is not prioritized to be straightened out anytime soon.

Using if <object> is (not) None is a recommended workaround.

Related