asteroid4u
asteroid4u

Reputation: 135

Global modules across the files in python

Any one help me how to declare global variables across the python files

In Below python file i have declared the global variable var1:

 File locations for settings.py:
/usr/lib/python2.7/site-packages/project/settings.py

settings.py

global var1
var1 = ""

python file2.py:

 Location:
/usr/lib/python2.7/site-packages/file2.py

file2.py

from dev import fullchip
from project import settings
a = 10
b = 20
fullchip.count (a, b)
print var1

script fullchip.py

 location
 /usr/lib/python2.7/site-packages/dev/fullchip.py 

script fullchip.py

 from projects import settings
 def count(a, b):
     global var
     var1 = a + b

I am running file2.py

I am expecting var1 to print "30" but i am getting var1 not defined. Basically I want to use var1 as global variables across all the files

Upvotes: 0

Views: 58

Answers (1)

stovfl
stovfl

Reputation: 15533

Question: I am expecting var1 to print "20" but i am getting var1 not define

  1. Misspelled project and projects

    File locations for settings.py:
    /usr/lib/python2.7/site-packages/project/settings.py

    but uses

    from projects import settings

  2. This works for me, no global required:

    from dev import fullchip
    from project import settings
    
    a = 10
    b = 20
    fullchip.count (a, b)
    print(settings.var1)
    

Output

30

Upvotes: 1

Related Questions