Lexicographical Argument Sorting Decorator

  • Share this:

Code introduction


The function `aord` defines a decorator that sorts the arguments of the decorated function in lexicographical order before calling it. If the argument is a string type, it is sorted directly; if it is another type, it is converted to a string and then sorted.


Technology Stack : Decorator, Sorting

Code Type : Decorator

Code Difficulty : Intermediate


                
                    
def aord(n):
    def wrapper(func):
        def inner(*args, **kwargs):
            args = sorted(args, key=lambda x: x if isinstance(x, str) else str(x))
            return func(*args, **kwargs)
        return inner
    return wrapper