0

I have a question; I have some code for a thread:

if __name__ == "__main__":

    x = makeThread("Thread 1", thread_function, ThreadKeyArg = "PersonalKey\n")
    xx = makeThread("Thread 2", thread_function, ThreadIDArg = 11111)
    xxx = makeThread("Thread 3", thread_function, ThreadKeyArg = "AnotherPersonalKey\n")
    xxxx = makeThread("Thread 4", thread_function, ThreadIDArg = 1234)

then, I ask if x is in locals() or globals(). If the statement is true, then print("something") occurs. Here is that section of code:

if x in locals() or globals():
    print("something")

This code does make the if statement true, so it does print the text. However, when I put if x in locals() or if x in globals(), neither times do they print("something"). Now, this does not cause me any problems, I am just wondering why this is so.

  • 2
    Does this answer your question? [Why does "a == x or y or z" always evaluate to True?](https://stackoverflow.com/questions/20002503/why-does-a-x-or-y-or-z-always-evaluate-to-true) – ForceBru Dec 08 '21 at 23:12
  • Also see: https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-single-value – ForceBru Dec 08 '21 at 23:13

1 Answers1

1

There are two issues going on here.

  1. x in locals() or globals() does not distribute the in test to check both dictionaries. It works like (x in locals()) or globals(), which, if globals() is not empty, will always be truthy. If you want to test membership in each dict, you want x in locals() or x in globals()

  2. x in locals() doesn't do what you want. You probably mean "x" in locals(). Otherwise you're testing if the value of x is also a key in the locals() dict (e.g. a variable name). Since the value of x is probably some kind of thread object, that's never going to work. Use a string if you want to test for the literal variable name "x".

Blckknght
  • 100,903
  • 11
  • 120
  • 169