0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I'd suggest "write to" rather than "access", but yes.
No. But I am able to access other variables. The problem is occurring due to if args.extra_devices is not None: extra_devices = args.extra_devices. If I remove that line, it works fine.
@Pretty, did you actually try the suggestion given here before commenting?
@Pretty That's because you didn't change the variable in that function. In this situation, the interpreter will define that variable is a global variable. But when you may change the variable's value in some functions, the variable will be defined as a local variable except you assign it is a global variable.
@Huan-YuTseng, yes, your interpretation is definitely correct; it's only a question of how best to clearly communicate it to the reader. If there were no writes anywhere within the function, after all, the global would not be shadowed by any local; that can be a subtle distinction for folks who are new to follow.
|

Your Answer

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