Search code examples
importdecorator

How to apply a decorator with arguments to an imported function


This similar to a previous question but not quite.

Like the other question, I want to apply a decorator to an imported function, but in my case, my decorator requires arguments

Working

from flask_restx import Namespace
from . import exceptions as e

api = Namespace('v2', 'API Version 2' )

@api.errorhandler(e.MissingPrompt)
def handle_bad_requests(error):
    '''Namespace error handler'''
    logger.warning(error.log)
    return({'message': error.specific}, error.code)

But I want to move handle_bad_requests() to its own file

so I want it like

from flask_restx import Namespace
from . import exceptions as e

api = Namespace('v2', 'API Version 2' )

@api.errorhandler(e.MissingPrompt)
e.handle_bad_requests # ??

I tried like the other answers here suggested like this

handle_bad_requests  = api.errorhandler(e.handle_bad_requests, e.MissingPrompt)

But that just gives me an error I am sending too many arguments


Solution

  • I just discovered the answer nested within the comments of a previous answer

    handle_bad_requests = api.errorhandler(e.MissingPrompt)(e.handle_bad_requests)
    

    And that seems to work fine.

    The double parentheses would never have occured to me