1

I'm trying to increment a python global var from another script, but it doesn't seem to be updating. Am I doing something wrong here?

I run func() multiple times during the script execution and it never seems to update globVal

script 1:

def func():
    from script2 import globVal
    global globVal
    print "glob val is " + str(globVal)
    globVal = globVal + 1

script 2 (different file):

global globVal
globVal = 1
3
  • Once you have found an answer which works for you, please click the tick next to that answer to accept it. This lets other people with your problem know which solution worked for you. Commented Aug 18, 2017 at 19:39
  • FYI, global variables are seldom used in practice. You should encapsulate them when possible. docs.quantifiedcode.com/python-anti-patterns/maintainability/… and wiki.c2.com/?GlobalVariablesAreBad Commented Aug 18, 2017 at 19:43
  • You should note that when you import globVal and declare it as global, it will take precedence over an existing globVal, if there is such variable. You may want to forgo the func function entirely, as well as the global declarations. Commented Aug 18, 2017 at 19:43

1 Answer 1

5

Yes, you are doing something wrong (answering your first question)

You should move from script2 import globVal to the top of script2 as that value is being imported each time as 1. After moving the import to the top, the globVal variable should update.

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

1 Comment

Thanks, that fixed it.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.