1
def doSomething(index):
    if index == 0:
        while flag1:
            do stuff
    elif index == 1:
        while flag2:
            do stuff

    ...

In a multi-threaded environment, flag1 and flag2 are booleans(global variables) which would be modified somewhere else. It would be really elegant if I could do it like this:

def doSomething(index):
    while (put either flag1 or flag2 here according to index):
        do stuff

Is there a way to achieve this?

EDIT:

1. Saw a few people suggesting list, the thing is, list like this flags = [flag1, flag2, flag3, ...] assumeflag1 = True, flag2 = False, flag3 = True, this makes flags = [True, False, True], and if you modify flag1 = False somewhere else in another thread, flags won't change accordingly, so this definitely won't work.

enter image description here

2. Actually I found one original answers suggesting while [flag1, flag2, flag3, ...][index], and it actually works! Just don't know why he deleted his answer?

Interesting Part:

Just tested the following part:

def doSomething(index):
    flags = [flag1, flag2, flag3]
    while flags[index]:
        do stuff

And it WON'T work, but interestingly enough, this actually works:

def doSomething(index):
    while [flag1, flag2, flag3][index]:
        do stuff

So I suppose [flag1, flag2, flag3][index] actually return the original variable? Anybody can explain a bit more?

1
  • The question isn't really about global variables; the same sort of flow could be required with local variables just as well. Could you come up with a better question title please?
    – tripleee
    Jul 31, 2014 at 3:36

5 Answers 5

2

I believe what happen is when you create list or dictionary of reference, reference of a literal does not change.

When you create list of flags, flags[0] points to what flag1 points to, which is False.

When you reassign values to flag1, you are changing to what the flag1 is pointing, but flags[0] is still pointing to False.

One way you can work around this is to add one more layer of object wrapper. If your boolean values are contained in an object, since the reference in the list points to what labels point to, which is the object, change in fields will be reflected.

In fact, why not just use flags as a global variable? If the script is smart enough to hardcode changes in one specific flag at a particular place, perhaps we can replace

flag1 = False

with

flags[0] = False

or even with a message-passing

flags[mess] = False

flags can be list, dict, or normal objects. The good old message-passing style all over the place!

1

There is probably a more elegant design solution to this problem, but to get around variables not being updated in a list, simply wrap them in a class

>>> class Flag():
    def __init__(self,flag):
        self.flag = flag


>>> flag_1 = Flag(True)
>>> flag_2 = Flag(False)
>>> flag_list = [flag_1, flag_2]
>>> flag_1.flag = False
>>> flag_list[0].flag
False
6
  • I think Shane wants to avoid creating a needless Wrapper class, as he probably already has code configured to use a different class. Jul 31, 2014 at 3:21
  • @ThomasHobohm Which is why I highlighted that this seems to be more of a design issue, and looks like it is lending itself towards refactoring to achieve the desired effects (see the high coupling already between global flags -- what if they change class or type etc?)
    – C.B.
    Jul 31, 2014 at 3:25
  • You do realize that the code in his post is just an example, right? Jul 31, 2014 at 3:27
  • @ThomasHobohm you mean do stuff isn't valid python syntax? :)
    – C.B.
    Jul 31, 2014 at 3:27
  • I mean, he probably has way more complex code, in which refactoring would take way longer. He's also using multithreading, so he probably can't pass these variables around to all the different threads easily without making them Global. Jul 31, 2014 at 3:35
0

You use the ternary operator.

def doSomething(index):
    while (flag1 if index else flag2):
        do stuff
0

To expand on Ethan's answer:

You can have a list of all the indexes, and then structure your while statement like this:

while flags[index]:
    # do stuff

You said that you edit the flag1 and flag2 objects (in other parts of the code, I assume), and that they don't change in the list. You can just reconstruct the list right before your while loop:

while [flag1, flag2, flag3, ...][index]:
    # do stuff

To have the "switch" statement you described, you'd need to have access to all your flag variables inside the doSomething function anyway, so it would be trivial to reconstruct the list.

7
  • looks like there are only value_one and value_two two choices?
    – Shane
    Jul 31, 2014 at 3:00
  • Yes, ternaries only give you two choices. Do you want to have a while statement which can handle a bunch of different choices on one line? Jul 31, 2014 at 3:05
  • Well, yes, that's the reason I want to find an elegant way of doing it.
    – Shane
    Jul 31, 2014 at 3:09
  • NO, this won't work, see my edit. The only way to make it work is to structure the list directly into while sentence, and I still don't know why that guy ccame up with this deleted his answer.
    – Shane
    Jul 31, 2014 at 3:26
  • Yes, it will work. I literally just recommended the exact same thing that you said would work, in a slightly different format. You reconstruct the list inside the function each time. The only different is that I'm creating a variable for clarity, while the other person isn't storing the reconstructed list in a variable. Jul 31, 2014 at 3:28
0

If you can have several index values, then have a list of flags:

flags = [flag0, flag1, flag2, flag3, flag4]

then you can use the index to query the appropriate flag:

def doSomthing(index):
    while(flags[index]):
        do_stuff()

Edit:

For this to work, the global variables are not flag0, flag1, etc., but instead the global variable is flags, the list. The threads then modify flags[flag1] and flag1 is 1.

FLAG0, FLAG1, FLAG2, FLAG3 = range(4)
flags = [False] * 4

Or, to use the new Enum module (enum34 is the backport):

from enum import Enum

class Flags(Enum):
    flag0 = 0
    flag1 = 1
    flag2 = 2
    flag3 = 3
    def __init__(self, value):
        self._boolean = False
    def __nonzero__(self):
        return self._boolean
    def set(self):
        "make the flag be True"
        self._boolean = True
    def clear(self):
        "make the flag be False"
        self._boolean = False

print Flags.flag0, bool(Flags.flag0)
Flags.flag0.set()
print Flags.flag0, bool(Flags.flag0)

the_flag_I_care_about = Flags.flag1
print the_flag_I_care_about, bool(the_flag_I_care_about)
the_flag_I_care_about.set()
print the_flag_I_care_about, bool(the_flag_I_care_about)
the_flag_I_care_about.clear()
print the_flag_I_care_about, bool(the_flag_I_care_about)

Oh, and just to be clear -- use better names than flag0, etc. :)

4
  • This won't work. flag0, flag1 get modified somewhere else, but flags (the list) won't change accordingly
    – Shane
    Jul 31, 2014 at 2:40
  • But it's a list of references; the values in the list are the values of the actual flag variables. +1!
    – tripleee
    Jul 31, 2014 at 3:39
  • It's not a list of references! Python lists are pass-by-value, except for classes. Jul 31, 2014 at 3:50
  • @Shane: My apologies for not explaining myself clearly -- flags is meant to be the replacement global variable. I also added an example using the new Enum data type. Jul 31, 2014 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.