0

this is probably a silly question but I'm a little bit struggling to make it work :

Let's say I have two files :

script1.py :

    myValue = 0

def addition():
    global myValue
    myValue += 1

if __name__ == '__main__':
    addition()
    print(myValue)

script2.py :

def getMyValue():
    from script1 import myValue
    print(myValue)

getMyValue()

Output : 0

I want my 2nd script to access the updated value so I can get '1' as output. How do you think I can do it properly ?

Thanks for your replies

2
  • 2
    It looks like myValue is only updated unless you actually call the addition() function. What is the more general problem you're trying to solve? Because in general mutable global variables are not a good way to pass around data. Commented Jun 27, 2021 at 11:42
  • @Iguananaut yes, that's it, i only need to get myValue value updated so the second script can get the updated value (1),. I'm not really familiar with the if __name__ == '__main__' but it returns 0. I'm surely missing something. Commented Jun 27, 2021 at 11:49

1 Answer 1

2

The variable myValue is not updated in script2.py as you don't call the addition() function by importing script1. That is due to the condition if __name__ == '__main__' which ensures that every following logic is only executed if you run the script itself. If you import script1 into another script the condition if __name__ == '__main__' becomes False and none of the below code will run. You could either just call addition() directly in script1, which would not be a very clean solution - script1:

myValue = 0

def addition():
    global myValue
    myValue += 1

addition()

or reconsider if addition() actually needs to operate on a global variable. Be aware that globals in python are just global within a module and not across several modules, so importing both the variable and the function into script 2 would not allow you to call addition() in script2 with the expected effects. However, i would suggest making it accept a parameter like this - script1:

myValue = 0

def addition(a_value):
    a_value += 1
    return a_value

if __name__ == '__main__':
    myValue = addition(myValue)
    print(myValue)

and then call the addition function in script2, for example as follows - script2:

from script1 import *

def getMyValue():
    my_new_value = addition(myValue)
    print(my_new_value)

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

1 Comment

Thanks for your reply, I just have a question, i the addition function is called multiple times, myValue will stay at 1, how do I do if I want this to go up to 2, 3, 10... and retrieve it in my second script ? Thanks !

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.