+3 votes
in Machine Learning by (9.6k points)
recategorized by
I want to check the presence or absence of a method in an object at run time. Is there any function to check it?

E.g., Let us say I want to check whether the LogisticRegressionClassifier() of scikit-learn has the predict_proba() method. How can I check it?

1 Answer

+2 votes
by (42.1k points)

You can use the python function hasattr() to find whether an attribute/method is present in an object. It will return True if the attribute is present in the object, otherwise, False.

Here is an example to check if "split" method is present in StratifiedKFold():

from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=2)

if not hasattr(skf, "split"):
    print("split method is not found")
else:
    print("split method is found")

Since StratifiedKFold has split() method, the code will execute the else part.

Related questions

...