Search code examples
pythonpython-decorators

python decorator for only one function is not useful in generally, right?


I know that decorator can expand function ability without original function change. so case of Real World Examples, decorator is useful about logging or Timing Functions.

and my question is.. I make decorator for only one function, not other function. decorator is dependent to original function like this.

def read_file(file_path):
    file_data=''
    with open(file_path) as f:
       file_data = f.read()
    return file_data

def only_compare_file_value_decorator(f):
    def wrapper(*args):
        d1 = read_file(args[0]) 
        d2 = read_file(args[1])
        return f(d1,d2)
    return wrapper

@only_compare_file_value_decorator
def compare_file_value(*args):
    return compare_hash(args[0], args[1])

In case above, only_compare_file_value_decorator is only for function compare_file_value.. I wonder this decorator is good or not in generally. please tell me your advice.


Solution

  • As stated in Zen of Python Simple is better than complex. Adding wrapper in this case only obfuscates the code and makes it harder to read. Knowing how to write them is important, but your code would be easier to read if you moved only_compare_file_value_decorator implementation into compare_file_value body. You also use *args when you really expect 2 filenames as input, which also obfuscates the code.

    def read_file(file_path):
        file_data=''
        with open(file_path) as f:
           file_data = f.read()
        return file_data
    
    
    def compare_file_value(file_name_1, file_name_2):
        file1, file2 = read_file(file_name_1), read_file(file_name_2)
        return compare_hash(file1, file2)