Search code examples
pythonoopchaining

Python class methods chaining


I do have a class:

class BaseModel:

    def __init__(self):
        pass

    def read_data(self):
        df = ...
        return df

    def transform_input(self, df):
        df = ...
        return df

    def execute(self, df):
        df = ...
        return df

    def run(self):
        data = self.read_data()
        data = self.transform_input(data)
        data = self.execute(data)

How to avoid these methods call one after the other? is it possible to do sth like:

data = self.read_data().transform_input().execute()

?

Is it possible to chain somehow these methods and solve the issue of passing the argument (data) withing this methods chain?


Solution

  • These are not class methods, they are instance methods. For method chaining, it is imperative that each method returns an object that implements the next method in the chain. Since all of your methods are instance methods of BaseModel, you need to return an instance of BaseModel (or a descendant of it). That obviously means that you cannot return df (since presumably df is not an object of BaseClass). Store it in the instance and retrieve it at the end of the chain.

    class BaseModel:
    
        def __init__(self):
            pass
    
        def read_data(self):
            self.df = ...
            return self
    
        def transform_input(self):
            self.df = ...
            return self
    
        def execute(self):
            self.df = ...
            return self
    
        def run(self):
            data = self.read_data().transform_input().execute().df
    

    For difference between instance methods and class methods, this answer gives a nice overview.