Search code examples
pythonpython-3.xprogram-entry-point

Access variable in main function from other script


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


Solution

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