1

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)
user
  • 21
  • 4
  • 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 problem – JrmDel Apr 29 '20 at 16:10

3 Answers3

5

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).

afghanimah
  • 705
  • 3
  • 11
5

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))
Treatybreaker
  • 776
  • 5
  • 9
0

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))