Get variable declared in function outside of developer

Asked

Viewed 33 times

0

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

Stages

  1. Capture variable file before function read_file be called
  2. "Scan" filing cabinet
  3. Return or not the function that called the decorator

I have tried in many ways and agree that I have found no way to do this, even using the module inspect from 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 taken as Object file.

1 answer

1


In Python, explicit is better than implicit. The way you’re doing it would be hiding rules inside the decorator and it would affect the readability of the code. Because having a function that reads only one file doesn’t seem to make much sense; it would be better if you passed the file name 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 on Repl.it

So the exit would be something like:

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

For the object devolver, which in your case will be the condition to define whether the function will be executed or not, is defined as True, causing the function to perform normally. If you set it to False, the exit will be:

Escaneando o arquivo arquivo.txt

Not running the function.

  • That’s not exactly what I thought I’d develop. The function I set up in read_file itself, was just an example, but I thought of something bigger as, a function with manipulation with many files. However, you made me think of a number of things, such as readability, usability, maintenance, and omission/error generation that will surely happen. In a way you helped me indirectly, so I just have to thank you. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.