Home > OS >  Python replace method with a decorator
Python replace method with a decorator

Time:10-01

I have a Python dictionary basket={fruit:'apple',vegetable:'kale'}

and a helper function , that wherever it sees the words fruits and vegetables in the Execution query , it will replace it with apple and kale respectively.

Helper function :

      def replaceQuery(self,query,**basket):


            for key , value in basket.items():

                if key in query:
                    query=query.replace(key,value)

            return query

Next , I am using the query returned from this method and passing on to the execution method

      query =replaceQuery(query,basket)
      
      executeQuery(Client, query)

The execution Method is as below:

     def executeQuery(Client,query):

        result=Client.query(query)

I have been learning decorators and was wondering if i can add a decorator on the executeQuery() method , so that every time it gets called , it will first replace teh Query string to replace all the fruits and vegetables values .Something similar to this

@replaceQuery
def executeQuery(Client,query)
   ......
   ......

Any help or suggestions with adding a decorator to this process will be helpful

CodePudding user response:

You can achieve the same functionality using decorator, as shown in example below

def replaceQuery(decorated):
    @wraps(decorated)
    def replace(Client, query, basket):
        # code to run before the decorated func
        for key , value in basket.items():
            if key in query:
                query=query.replace(key,value)

        # running the decorated func
        return decorated(Client, query, basket)
    return replace

@replaceQuery
def executeQuery(Client, query, basket):
    ......
    ......

In Python functions are like any other object, by adding @replaceQuery decorator to executeQuery function, you actually call replaceQuery with executeQuery replaceQuery(executeQuery) so decorated object refers to executeQuery func. When running executeQuery() replace() will be invoked, so you can add the functionality you want to get executed before running the decorated function (executeQuery) in replace func, and after that to call executeQuery.

  • Related