wiki:Orange25/NameDeprecationDecorators

Version 3 (modified by marko, 3 years ago) (diff)

Aleš has written function decorators to help us maintain backward compatibility when the names of object attributes, methods or keyword arguments of function change: deprecated_keywords and deprecated_members. Both are in Orange.misc.

WARNING: Do not use deprecated_members as s decorator, because python 2.5 does not support class decorators. Run it explicitly, as a function (see the example below).

A use case example. ImputeLearner in orngImpute.py (prior to the development of Orange 2.5) looked like this:

class ImputeLearner(orange.Learner):
   def __new__(cls, examples = None, weightID = 0, **keyw):
       self = orange.Learner.__new__(cls, **keyw)
       self.dontImputeClassifier = False
       self.__dict__.update(keyw)
       if examples:
           return self.__call__(examples, weightID)
       else:
           return self
       
   def __call__(self, data, weight=0):
       trained_imputer = self.imputerConstructor(data, weight)
       imputed_data = trained_imputer(data, weight)
       baseClassifier = self.baseLearner(imputed_data, weight)
       if self.dontImputeClassifier:
           return baseClassifier
       else:
           return ImputeClassifier(baseClassifier, trained_imputer)

For Orange 2.5 we have modified it (from Orange/feature/imputation.py):

class ImputeLearner(orange.Learner):
   def __new__(cls, examples = None, weight_id = 0, **keyw):
       self = orange.Learner.__new__(cls, **keyw)
       self.dont_impute_classifier = False
       self.__dict__.update(keyw)
       if examples:
           return self.__call__(examples, weight_id)
       else:
           return self

   def __call__(self, data, weight=0):
       trained_imputer = self.imputer_constructor(data, weight)
       imputed_data = trained_imputer(data, weight)
       base_classifier = self.base_learner(imputed_data, weight)
       if self.dont_impute_classifier:
           return base_classifier
       else:
           return ImputeClassifier(base_classifier, trained_imputer)

To keep the function backwards compatible we need to to add the following code to Orange/feature/imputation.py:

ImputeLearner = Orange.misc.deprecated_members(
 {
     "dontImputeClassifier": "dont_impute_classifier",
     "imputerConstructor": "imputer_constructor",
     "baseLearner": "base_learner",
     "weightID": "weight_id"
 })(ImputeLearner)

In orngImpute.py we just need to import it:

from Orange.feature.imputation import ImputeLearner

Everything else is magic. Check the documentation and the source code for Orange.misc for details. It is also possible to decorate a single function with the deprecated_keywords.