user1792899
user1792899

Reputation:

Accessing global variable

All I want is to assign some initial value to the variable 'extra_devices' and if the user specifies some value to this variable at the run time, the default value gets replaced with the user's specified value. I am adding a minimal code snippet to show what I am doing.

While running this program, if I do not specify 'extra_devices', the program fails to run saying 'UnboundLocalError: local variable 'extra_devices' referenced before assignment', but I fail to understand the reason since I have already assigned the value to it. However, the program works fine if I specify 'extra_devices' at runtime. Anyone got any reasoning for this behavior?

Notice variable 'abc' prints fine in main().

    #/usr/bin/python
    import argparse
    extra_devices=10
    abc = 1
    def main():

        parser = argparse.ArgumentParser(description='')
        parser.add_argument('-extra_devices','--extra_devices',help='extra_devices',required=False)
        args = parser.parse_args()
        if args.extra_devices is not None: extra_devices = args.extra_devices
        print "abc="+str(abc)

        print "extra_devices = "+str(extra_devices)

    if __name__ == '__main__':
        main()

Upvotes: 0

Views: 60

Answers (1)

Huan-Yu Tseng
Huan-Yu Tseng

Reputation: 566

Add one line in the function:

global extra_devices

Then you can write to the global variable in the function.

The reason is because you may change that variable in the function, and the interpreter will define it as a local variable instead of global variable for protecting the global variable, except you assign that variable is a global variable.

Update:

Add the reason.

Upvotes: 2

Related Questions