Search code examples
pythonextern

How to share global variables between files in Python like C


i have 2 files

#foo.py
 global x
 def foo():
   x = 8


#main.py
from conf import *

 if __name__ == "__main__":
 foo()

how to get the X value in main.py file i have to use only 2 files here now if print or store x to other variable it has to print 8


Solution

  • You can do something like this to get varaible x in main.py , if you declare x as global inside foo() that mean you will be accessing the global x not local x.

    #foo.py
     x =10
    def foo():
       x = 8
       print(" in foo x= " ,x)
    
    
    #main.py
    from conf import *
    from foo import x, foo
    
    if __name__ == "__main__":
       print(" x imported from foo.py  = ", x)
       foo()
    

    OUTPUT

    x imported from foo.py  =  10
    in foo x=  8