0

I have two files:

script1.py :

myValue = 0

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

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

script2.py :

from script1 import *

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

getMyValue()

When script1 is executed it returns 2, and this is what I want. But when script2 is executed, it returns 1. How can I get the preserved result 2 from script2?

If I want to execute addition() multiple times and always get the updated result in script2 instead of getting 1 every time? Thank you for your replies.

Rolv Apneseth
  • 2,078
  • 2
  • 7
  • 19
Leomax
  • 83
  • 5
  • "How can I get the preserved result 2 from script2" - there has never been a `2` anywhere in all of this, so I fail to see what your question means. Could you clarify? – Thierry Lathuille Jun 27 '21 at 13:16
  • What I am trying to say is that when script1 is executed, i get the output 2, because the addition() function is executed 2 times. I need to get the same output with script2, but it returns only one. Like i want to get the updated variable myValue at 2. Sorry for my english. – Leomax Jun 27 '21 at 13:18
  • 1
    OK, but when you `import` it instead of running it as a standalone script, the part in `if __name__ == '__main__':` doesn't run, so there is no `2` anywhere. Maybe your question is actually https://stackoverflow.com/questions/419163/what-does-if-name-main-do – Thierry Lathuille Jun 27 '21 at 13:20
  • 1
    Don't import globals with `import *` - it doesn't do what you think it does. (Globals and `import *` are rarely a good idea even on their own, but put them together and you get even more problems.) – user2357112 Jun 27 '21 at 13:20
  • Also what Thierry said. – user2357112 Jun 27 '21 at 13:21
  • What is the end goal for your code? There's likely a better way to do it than having a variable in `script1` that you need in `script2`, i.e. making the code in `script1` a class, but it depends on what you ultimately want done with your code – Rolv Apneseth Jun 27 '21 at 13:37
  • 1
    @RolvApneseth I am actually completely rewriting my code so it will be a more OOP approach. – Leomax Jun 27 '21 at 14:22
  • 1
    That's probably for the best, hope it works out for you – Rolv Apneseth Jun 27 '21 at 14:23

0 Answers0