Get declared variable in the function outside the decorator

0

I tried with the module inspect but could not get the result. The concept is: "scan" a file through a decorator .

Steps

  • Capture variable file before function read_file will be called
  • "Scan" file
  • Return or not the function that called decorator
  • I have tried in several ways and I agree that I did not find any way to do this, even using the inspect module of the Standard Python library.

    def scan_files(funcs):
        print(funcs.__code__.co_varnames)
        return funcs
    
    @scan_files
    def read_file():
        file = open('arquivo.txt', 'w')
        file.close()
        with open('arquivo.txt', 'w') as new_file: ...
    

    PS: for reasons of readability omit some factors, such as, functions with named arguments or not, variable not having the fixed name being necessary to know the type considered as object file.     

    asked by anonymous 17.12.2017 / 15:17

    1 answer

    1

    In Python, explicit is better than implicit. In the way you are doing you would be hiding rules inside the decorator and this would affect the readability of the code. Also because having a function that reads only one file does not seem to make much sense; it would be best if you passed the filename by parameter.

    def scanner(function):
        def wrapper(filename):
            print(f"Escaneando o arquivo {filename}")
            ...
            devolver = True  # Define se a função deverá ser executada ou não
            if devolver:
                return function(filename)
            return None
        return wrapper
    
    @scanner
    def read_file(filename):
        print(f"Abrindo o arquivo {filename}")
        with open(filename, 'w') as stream:
            ...
    
    if __name__ == '__main__':
        read_file('arquivo.txt')
    

    See working at Repl.it

    So the output would be something like:

    Escaneando o arquivo arquivo.txt
    Abrindo o arquivo arquivo.txt
    

    Because the devolver object, which in its case is the condition of whether the function is executed or not, is set to True , causing the function to execute normally. If I set it to False , the output will be:

    Escaneando o arquivo arquivo.txt
    

    Not running the function.

        
    18.12.2017 / 11:56