简体   繁体   中英

Conditionally modify global variable

I'd like to do something like this, but I get a SyntaxWarning and it doesn't work as expected

RAWR = "hi"
def test(bool):
    if bool:
        RAWR = "hello"   # make RAWR a new variable, don't reference global in this function
    else:
        global RAWR
        RAWR = "rawr"    # reference global variable in this function
    print RAWR           # if bool, use local, else use global (and modify global)

How do I get this to work? Passing in True or False modifies the global variable.

You cannot. Within a scope, a specific name refers either to a local variable, or to a non-local (eg global, or from an outer function) variable. Not both. The global RAWR line makes RAWR a global for the entire scope (that's why you get a warning, it doesn't do what you think it does), just like assignment to a variable makes it local for the entire scope. Edit: Thanks to veredesmarald, we now know it is in fact a syntax error in Python 2. This half of my answer only applies to Python 3 apparently.

You should just use a differently-named local variable, and in the branch where you want to "promote" it to a global, set the global and the local variable. (Or just don't use globals at all.)

The only easy way you can go would be

RAWR = "hi"
def test(newone):
    if newone:
        lR = "hello"   # make RAWR a new variable, don't reference global in this function
    else:
        global RAWR
        lR = RAWR      # reference global variable in this function
    print lR           # if bool, use local, else use global (and modify global)
    # modify lR and then
    if not newone:
        RAWR = lR

Another way, however, could be to abuse the concept of classes and objects to your purposes.

class store_RAWR(object):
    RAWR = "hi"
    def __init__(self, new): self.RAWR = new

def test(newone):
    if newone:
        myR = store_RAWR("hello") # get a (temporary) object with a different string
    else:
        myR = store_RAWR # set the class, which is global.
    # now modify myR.RAWR as you need

But this requires other program parts which use the global name to be changed as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM