Search code examples
pythonimportglobal-variables

want to use the variable in this file not in the import one


Hey guys here is the problem that I have faced in my project. Here I use a simple example to explain it. When I try to run the main.py, I want to use the variable in this module not in the helper, but the output result is always 2 even when i delete the global variable "a". Is there any way without inputting the function argument? Hope someone can help :(

helper.py

a = 2
def test():
   print(a)

main.py

from helper import *

del globals()["a"]
if __init__ == "__main__":
    a = 10
    test()


Solution

  • You could just modify the attribute:

    main.py

    import helper
    
    if __name__ == "__main__":
        helper.a = 10
        helper.test()
    

    Output:

    10
    

    Edit:

    You could try:

    helper.py

    a = [2]
    def test():
       print(a[0])
    

    main.py

    from helper import *
    
    if __name__ == "__main__":
        a.clear()
        a.append(10)
        test()
    

    Output:

    10