mardi 15 septembre 2020

How to choose which decorator to apply based on condition?

Can decorators be applied based on condition ? Below is a trivial example:

import os


def bold_decorator(fn):
    def wrapper(*args, **kwargs):
        return '**' + fn(*args, **kwargs) + '**'
    return wrapper

def italic_decorator(fn):
    def wrapper(*args, **kwargs):
        return '_' + fn(*args, **kwargs) + '_'
    return wrapper


if os.environ.get('STYLE'):  
    @bold_decorator
else:
    @italic_decorator
def create_text(text=''):
    return text

if __name__ == '__main__':
    print(create_text('Decorator decisions'))

What I want is, when environment variable is set, to apply bold_decorator. And when it's not set, use italic_decorator. I'm using Flask framework for JWTs which has decorators jwt_required and jwt_optional in which I can't modify source of these decorators. I'm trying to find solution to this problem. Any help would be appreciated

Aucun commentaire:

Enregistrer un commentaire