Essentially, the variable 'exists' doesn't return. The output is "false, true, false," but I cannot see why it should be. As can be seen from the code, I have tried making the variable 'exists' global to no effect.
I've looked around and found two similar questions- Python--Function not returning value, Python: Return possibly not returning value, but cannot understand why my code doesn't work.
I'm aware that this question is very specific- if it's a silly mistake I've missed then I'll remove it, if it's a Python caveat then I'll see whether I can rephrase it.
import time
global exists
exists= False
def in_thread(exists):
print(exists)
time.sleep(2)
exists= True
print(exists)
return(exists)
in_thread(exists)
print(exists)
-
If you modify the value of a global variable, you need to call it at the beginning of your function. It might be a part of the problemJrmDel– JrmDel2020年04月29日 16:10:33 +00:00Commented Apr 29, 2020 at 16:10
3 Answers 3
The exists inside of in_thread is a different variable from the exists outside. If you want to use the same variable, use the global keyword:
exists = False
def somefunction():
global exists
exists = True
print(exists)
someFunction()
print(exists)
# False
# True
Also, in_thread looks like it's not returning anything because you're not assigning the result to anything (you're just printing a local version of exists).
Comments
You really should consider rewriting your function to be as such:
import time
def in_thread():
exists = False
print(exists)
time.sleep(2)
exists = True
return(exists)
print(in_thread())
It is returning, but it's returning its own version of exists when you declare exists outside the function. Instead consider creating it inside the function and call it in a print statement so it prints the output from the return.
This will lead to the output:
False
True
If you want to use your original function as written, you need to change your call to be in a print statement so you print the returned value:
import time
global exists
exists= False
def in_thread(exists):
print(exists)
time.sleep(2)
exists= True
print(exists)
return(exists)
print(in_thread(exists))
Comments
print(exists) returns the global variable value which is set to False.
To print the value from you function, you would need to call the function inside of print() print(in-thread(exists))
Replace: in_thread(exists) print(exists)
With: print(in_thread(exists))