469,313 Members | 2,639 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,313 developers. It's quick & easy.

Global variable declaration

440 256MB
Hi,

Global variables are declared before the class definition and after the modules of the application declaration.

Please correct me if I am wrong.

Thanks
PSB
Mar 22 '07 #1
24 8811
psbasha
440 256MB
I have a global variable declared in the Module.I have to make use of this global variable in another class/ class method.

Could anybody help me by explainning the sample code.

Thanks in advance
PSB
Mar 22 '07 #2
ghostdog74
511 Expert 256MB
I have a global variable declared in the Module.I have to make use of this global variable in another class/ class method.

Could anybody help me by explainning the sample code.

Thanks in advance
PSB
to use global variable from another class/method/function, just include the "global" keyword in that class/method/function.
Mar 22 '07 #3
bartonc
6,596 Expert 4TB
I have a global variable declared in the Module.I have to make use of this global variable in another class/ class method.

Could anybody help me by explainning the sample code.

Thanks in advance
PSB
While I highly recommend AGAINST gobals, mutable types will pass between modules:
Expand|Select|Wrap|Line Numbers
  1. #test.py
  2. # module holds globals
  3. globalList = []
  4. globalInt = 5
  5.  
  6. def printGlobals():
  7.     print globalList
  8.     print globalInt
  9.  
  10.  
  11. class GlobalModifier:
  12.     def ModifyGlobals(self):
  13.         global globalList
  14.         global globalInt
  15.  
  16.         globalList.append("hello")
  17.         globalInt = 7
  18.  
Expand|Select|Wrap|Line Numbers
  1. # module1.py
  2. # module1 uses golbal from test.py
  3. import test
  4. from test import globalList, globalInt
  5. globalList.append(0)
  6. test.printGlobals()
  7.  
  8. gm = test.GlobalModifier()
  9. gm.ModifyGlobals()
  10.  
  11. print globalList, globalInt
  12. test.printGlobals()
  13.  
but not immutable types:
[0]
5
[0, 'hello'] 5
[0, 'hello']
7
Mar 23 '07 #4
bvdet
2,851 Expert Mod 2GB
I have a global variable declared in the Module.I have to make use of this global variable in another class/ class method.

Could anybody help me by explainning the sample code.

Thanks in advance
PSB
The global namespace for a function or variable is always the module in which it was defined. To access the global variable from another module:
Expand|Select|Wrap|Line Numbers
  1. import yourModule
  2. localVariable = yourModule.globalVariable
Mar 23 '07 #5
bartonc
6,596 Expert 4TB
While I highly recommend AGAINST gobals, mutable types will pass between modules:
Expand|Select|Wrap|Line Numbers
  1. #test.py
  2. # module holds globals
  3. globalList = []
  4. globalInt = 5
  5.  
  6. def printGlobals():
  7.     print globalList
  8.     print globalInt
  9.  
  10.  
  11. class GlobalModifier:
  12.     def ModifyGlobals(self):
  13.         global globalList
  14.         global globalInt
  15.  
  16.         globalList.append("hello")
  17.         globalInt = 7
  18.  
Expand|Select|Wrap|Line Numbers
  1. # module1.py
  2. # module1 uses golbal from test.py
  3. import test
  4. from test import globalList, globalInt
  5. globalList.append(0)
  6. test.printGlobals()
  7.  
  8. gm = test.GlobalModifier()
  9. gm.ModifyGlobals()
  10.  
  11. print globalList, globalInt
  12. test.printGlobals()
  13.  
but not immutable types:
[0]
5
[0, 'hello'] 5
[0, 'hello']
7
The very good reason for this is that program errors are very hard to track down when more than one module is allowed to modify a variable.
Mar 23 '07 #6
bartonc
6,596 Expert 4TB
The very good reason for this is that program errors are very hard to track down when more than one module is allowed to modify a variable.
The mutable type to use between modules would be a class:
Expand|Select|Wrap|Line Numbers
  1. # test.py
  2. # class holds globals
  3.  
  4. import inspect # just for testing this idea
  5.  
  6. def PrintGlobRep():
  7.     for member in inspect.getmembers(globRep):
  8.         if not member[0].startswith('_'):
  9.             print member
  10.  
  11. class GlobalRepository:
  12.     globalList = []
  13.     globalInt = 5
  14.  
  15.  
  16. globRep = GlobalRepository()
# module1.py
Expand|Select|Wrap|Line Numbers
  1. # module1 uses Global Repository from test.py
  2.  
  3. import test # this does initialization of the Global Repository
  4. from test import globRep # get the class instance
  5.  
  6. test.PrintGlobRep()
  7. globRep.newGlobal = 12
  8. test.PrintGlobRep()
('globalInt', 5)
('globalList', [])
('globalInt', 5)
('globalList', [])
('newGlobal', 12)
Mar 23 '07 #7
psbasha
440 256MB
Expand|Select|Wrap|Line Numbers
  1. Sample.py
  2. iVar =1
  3.  
  4. class Sample1:
  5.  
  6.     def Func1(self):
  7.         global iVar
  8.         iVAr = 20
  9.  
  10.         print iVAr
  11.  
  12.     def Func2(self):
  13.         pass
  14.  
  15. class Sample2:
  16.  
  17.     def Func3(self):
  18.         pass
  19.  
  20.     def Func4(self):
  21.         global iVar
  22.         print iVar
  23.  
  24.         print iVar
  25.  
  26.  
  27. if __name__ == '__main__':
  28.  
  29.     obj1 = Sample1()
  30.     obj2 = Sample2()
  31.  
  32.     obj1.Func1()
  33.     obj2.Func4()
  34.     print iVar
  35.  
  36.  
>>>
20
1
1
1
>>>

But I was expecting the output will be

>>>
20
20
20
20
>>>

Can anybody help me in understanding the output.

Thnaks
PSB
Mar 23 '07 #8
bartonc
6,596 Expert 4TB
The mutable type to use between modules would be a class:
Expand|Select|Wrap|Line Numbers
  1. # test.py
  2. # class holds globals
  3.  
  4. import inspect # just for testing this idea
  5.  
  6. def PrintGlobRep():
  7.     for member in inspect.getmembers(globRep):
  8.         if not member[0].startswith('_'):
  9.             print member
  10.  
  11. class GlobalRepository:
  12.     globalList = []
  13.     globalInt = 5
  14.  
  15.  
  16. globRep = GlobalRepository()
# module1.py
Expand|Select|Wrap|Line Numbers
  1. # module1 uses Global Repository from test.py
  2.  
  3. import test # this does initialization of the Global Repository
  4. from test import globRep # get the class instance
  5.  
  6. test.PrintGlobRep()
  7. globRep.newGlobal = 12
  8. test.PrintGlobRep()
('globalInt', 5)
('globalList', [])
('globalInt', 5)
('globalList', [])
('newGlobal', 12)
Class instances can have "global" data by using class variables:
Expand|Select|Wrap|Line Numbers
  1. # class with shared variables
  2.  
  3. class WithSharedVariables:
  4.     ## class variables
  5.     globalList = []
  6.     globalInt = 5
  7.  
  8.     def __init__(self):
  9.         self.localInt = 11
  10.  
  11.     def printClassVars(self):
  12.         print WithSharedVariables.globalList
  13.         print WithSharedVariables.globalInt
  14.  
  15.     def IncGlobalInt(self):
  16.         WithSharedVariables.globalInt += 1
  17.  
  18.     def AppendGlobalList(self, item):
  19.         WithSharedVariables.globalList.append(item)
  20.  
  21.  
  22.  
  23. wsv1 = WithSharedVariables()
  24. wsv2 = WithSharedVariables()
  25.  
  26. wsv2.IncGlobalInt()
  27. wsv1.AppendGlobalList("hello")
  28.  
  29. wsv2.printClassVars()
  30.  
Mar 23 '07 #9
bartonc
6,596 Expert 4TB
Expand|Select|Wrap|Line Numbers
  1. Sample.py
  2. iVar =1
  3.  
  4. class Sample1:
  5.  
  6.     def Func1(self):
  7.         global iVar
  8.         iVAr = 20
  9.  
  10.         print iVAr
  11.  
  12.     def Func2(self):
  13.         pass
  14.  
  15. class Sample2:
  16.  
  17.     def Func3(self):
  18.         pass
  19.  
  20.     def Func4(self):
  21.         global iVar
  22.         print iVar
  23.  
  24.         print iVar
  25.  
  26.  
  27. if __name__ == '__main__':
  28.  
  29.     obj1 = Sample1()
  30.     obj2 = Sample2()
  31.  
  32.     obj1.Func1()
  33.     obj2.Func4()
  34.     print iVar
  35.  
  36.  
>>>
20
1
1
1
>>>

But I was expecting the output will be

>>>
20
20
20
20
>>>

Can anybody help me in understanding the output.

Thnaks
PSB
You've got a typo:
Expand|Select|Wrap|Line Numbers
  1. iVar =1
  2.  
  3. class Sample1:
  4.  
  5.     def Func1(self):
  6.         global iVar
  7.         iVAr = 20
  8.  
Mar 23 '07 #10
psbasha
440 256MB
Is the above sample piece of code for Global variable access is correct?.If not how to change the global variable value from '1' to '20' value.


-PSB
Mar 23 '07 #11
bartonc
6,596 Expert 4TB
Expand|Select|Wrap|Line Numbers
  1. Sample.py
  2. iVar =1
  3.  
  4. class Sample1:
  5.  
  6.     def Func1(self):
  7.         global iVar
  8.         iVAr = 20
  9.  
  10.         print iVAr
  11.  
  12.     def Func2(self):
  13.         pass
  14.  
  15. class Sample2:
  16.  
  17.     def Func3(self):
  18.         pass
  19.  
  20.     def Func4(self):
  21.         global iVar
  22.         print iVar
  23.  
  24.         print iVar
  25.  
  26.  
  27. if __name__ == '__main__':
  28.  
  29.     obj1 = Sample1()
  30.     obj2 = Sample2()
  31.  
  32.     obj1.Func1()
  33.     obj2.Func4()
  34.     print iVar
  35.  
  36.  
>>>
20
1
1
1
>>>

But I was expecting the output will be

>>>
20
20
20
20
>>>

Can anybody help me in understanding the output.

Thnaks
PSB
The error is here:
iVAr = 20
should be
iVar = 20
That will fix it.
Mar 23 '07 #12
psbasha
440 256MB
Thanks barton

Sorry, for me not noticing the correction of the bug.

Now I understood the concept of Global.I was familar with C++ global variables,then I thought the same concept should apply for any other programming language.

The concept is same "globally" :)

-PSB
Mar 23 '07 #13
bartonc
6,596 Expert 4TB
Thanks barton

Sorry, for me not noticing the correction of the bug.

Now I understood the concept of Global.I was familar with C++ global variables,then I thought the same concept should apply for any other programming language.

The concept is same "globally" :)

-PSB
That's really no problem.
So, what part of the globe are you located in, anyway?
Mar 23 '07 #14
psbasha
440 256MB
Expand|Select|Wrap|Line Numbers
  1. Sample1.py
  2. class CSample1:
  3.  
  4.     def Func1(self):
  5.         global iVar
  6.         iVar = 20
  7.  
  8.         print iVar
  9.  
  10.     def Func2(self):
  11.         pass
  12.  
Expand|Select|Wrap|Line Numbers
  1. Sample2.py
  2.  
  3. class CSample2:
  4.  
  5.     def Func3(self):
  6.         pass
  7.  
  8.     def Func4(self):
  9.         global iVar
  10.         print iVar
  11.  
Expand|Select|Wrap|Line Numbers
  1. Main.py
  2.  
  3. from Sample1 import CSample1
  4. from Sample2 import CSample2
  5.  
  6. if __name__ == '__main__':
  7.  
  8.  
  9.     obj1 = CSample1()
  10.     obj2 = CSample2()
  11.  
  12.     obj1.Func1()
  13.     obj2.Func4()
  14.     print iVar
  15.  
I am getting the following error

Traceback (most recent call last):
File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py" , line 307, in RunScript
debugger.run(codeObject, __main__.__dict__, start_stepping=0)
File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run
_GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 631, in run
exec cmd in globals, locals
File "[EDITED OUT]", line 11, in ?
obj2.Func4()
File "[EDITED OUT]", line 9, in Func4
print iVar
NameError: global name 'iVar' is not defined
>>>
Mar 23 '07 #15
psbasha
440 256MB
Is there any declaration or defintion has to be done in the Sample1 and Sample2 modules?


- PSB
Mar 23 '07 #16
bartonc
6,596 Expert 4TB
The mutable type to use between modules would be a class:
Expand|Select|Wrap|Line Numbers
  1. # test.py
  2. # class holds globals
  3.  
  4. import inspect # just for testing this idea
  5.  
  6. def PrintGlobRep():
  7.     for member in inspect.getmembers(globRep):
  8.         if not member[0].startswith('_'):
  9.             print member
  10.  
  11. class GlobalRepository:
  12.     globalList = []
  13.     globalInt = 5
  14.  
  15.  
  16. globRep = GlobalRepository()
That last line is special. It creates the global repository when the import is executed. It is accessed below by "from module import1". This is the best way to bring a mutable type variable for one module to another. Generally, though, this is done for "constants" (variables that should NEVER be assigned to).
# module1.py
Expand|Select|Wrap|Line Numbers
  1. # module1 uses Global Repository from test.py
  2.  
  3. import test # this does initialization of the Global Repository
  4. from test import globRep # get the class instance
  5.  
  6. test.PrintGlobRep()
  7. globRep.newGlobal = 12
  8. test.PrintGlobRep()
('globalInt', 5)
('globalList', [])
('globalInt', 5)
('globalList', [])
('newGlobal', 12)
Mar 23 '07 #17
psbasha
440 256MB
Usually "global" variables in any programming languages are used very rarely, and as Barton said,we dont know where the value of the global value be changed.It will be very difficult to track the value of it.

"global" variable main purpose is to make the life of the variable available from begining to the last of the program.

Thanks
PSB
Mar 24 '07 #18
bartonc
6,596 Expert 4TB
Usually "global" variables in any programming languages are used very rarely, and as Barton said,we dont know where the value of the global value be changed.It will be very difficult to track the value of it.

"global" variable main purpose is to make the life of the variable available from begining to the last of the program.

Thanks
PSB
That makes sense. Other options include database, config file, windows registry, etc. I uese the registry for startup values and SQL databse for shrare values.
Mar 24 '07 #19
psbasha
440 256MB
I tried as you suggested ,but still I am not able to solve the problem.

Suggest me the location where I have to change in my sample code.

Expand|Select|Wrap|Line Numbers
  1. Main.py
  2. from Sample1 import CSample1
  3. from Sample2 import CSample2
  4. from Sample1 import iVar
  5. from Sample2 import iVar
  6.  
  7. iVar = 1
  8. if __name__ == '__main__':
  9.  
  10.  
  11.     obj1 = CSample1()
  12.     obj2 = CSample2()
  13.  
  14.     obj1.Func1()
  15.     obj2.Func4()
  16.     print iVar
  17.  
Expand|Select|Wrap|Line Numbers
  1. Sample1.py
  2. class CSample1:
  3.  
  4.     def Func1(self):
  5.         global iVar
  6.         iVar = 20
  7.  
  8.         print iVar
  9.  
  10.     def Func2(self):
  11.         pass
  12.  
  13. iVar = CSample1()
  14.  
  15.  
  16.  
Expand|Select|Wrap|Line Numbers
  1. Sample.2py
  2. class CSample2:
  3.  
  4.     def Func3(self):
  5.         pass
  6.  
  7.     def Func4(self):
  8.         global iVar
  9.         print iVar
  10.  
  11. iVar = CSample2()
  12.  
  13.  
-PSB
Mar 25 '07 #20
psbasha
440 256MB
I tried as you suggested ,but still I am not able to solve the problem.

Suggest me the location where I have to change in my sample code.

Expand|Select|Wrap|Line Numbers
  1. Main.py
  2. from Sample1 import CSample1
  3. from Sample2 import CSample2
  4. from Sample1 import iVar
  5. from Sample2 import iVar
  6.  
  7. iVar = 1
  8. if __name__ == '__main__':
  9.  
  10.  
  11.     obj1 = CSample1()
  12.     obj2 = CSample2()
  13.  
  14.     obj1.Func1()
  15.     obj2.Func4()
  16.     print iVar
  17.  
Expand|Select|Wrap|Line Numbers
  1. Sample1.py
  2. class CSample1:
  3.  
  4.     def Func1(self):
  5.         global iVar
  6.         iVar = 20
  7.  
  8.         print iVar
  9.  
  10.     def Func2(self):
  11.         pass
  12.  
  13. iVar = CSample1()
  14.  
  15.  
  16.  
Expand|Select|Wrap|Line Numbers
  1. Sample.2py
  2. class CSample2:
  3.  
  4.     def Func3(self):
  5.         pass
  6.  
  7.     def Func4(self):
  8.         global iVar
  9.         print iVar
  10.  
  11. iVar = CSample2()
  12.  
  13.  
-PSB
I am getting the following output

>>>
20
<Sample2.CSample2 instance at 0x00CF65F8>
1
>>>
Mar 25 '07 #21
psbasha
440 256MB
Any suggestions on the above posting.

-PSB
Mar 26 '07 #22
bvdet
2,851 Expert Mod 2GB
Any suggestions on the above posting.

-PSB
Expand|Select|Wrap|Line Numbers
  1. # Main.py
  2. try:
  3.     reload(Sample1)
  4. except:
  5.     import Sample1
  6.  
  7. try:
  8.     reload(Sample2)
  9. except:
  10.     import Sample2
  11.  
  12. iVar = 1
  13. if __name__ == '__main__':
  14.  
  15.  
  16.     obj1 = Sample1.CSample1()
  17.     obj2 = Sample2.CSample2()
  18.  
  19.     print iVar
  20.     iVar = obj1.Func1()
  21.     print iVar
  22.     iVar = obj2.Func4()
  23.     print iVar
  24.  
  25. # Sample1.py
  26. class CSample1:
  27.  
  28.     def Func1(self):
  29.         iVar = 40
  30.         return iVar
  31.  
  32.     def Func2(self):
  33.         pass
  34.  
  35. # Sample.2py
  36. class CSample2:
  37.  
  38.     def Func3(self):
  39.         pass
  40.  
  41.     def Func4(self):
  42.         iVar = 20
  43.         return iVar
>>> 1
40
20
>>>

It seems like a lot of trouble though.
Mar 26 '07 #23
psbasha
440 256MB
Thanks for the reply

Is it not possible to get the results using the 'global'key word in different module?

-PSB
Mar 26 '07 #24
bvdet
2,851 Expert Mod 2GB
Thanks for the reply

Is it not possible to get the results using the 'global'key word in different module?

-PSB
Yes.
Expand|Select|Wrap|Line Numbers
  1. try:
  2.     reload(Sample1)
  3. except:
  4.     import Sample1
  5.  
  6. try:
  7.     reload(Sample2)
  8. except:
  9.     import Sample2
  10.  
  11. iVar = 1
  12. if __name__ == '__main__':
  13.  
  14.  
  15.     obj1 = Sample1.CSample1()
  16.     obj2 = Sample2.CSample2()
  17.  
  18.     print iVar
  19.     iVar = obj1.Func1()
  20.     print iVar
  21.     iVar = obj2.Func4()
  22.     print iVar
  23.     print Sample1.iVar
  24.  
  25. # Sample1.py
  26. class CSample1:
  27.  
  28.     def Func1(self):
  29.         global iVar
  30.         iVar = 40
  31.         return iVar
  32.  
  33.     def Func2(self):
  34.         pass
  35.  
  36. a =  CSample1()
  37. a.Func1()
>>> 1
40
20
40
Mar 27 '07 #25

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

reply views Thread by Joseph George | last post: by
2 posts views Thread by Thomas Matthews | last post: by
6 posts views Thread by rick | last post: by
44 posts views Thread by fabio | last post: by
16 posts views Thread by Roman Ziak | last post: by
4 posts views Thread by kuhrty | last post: by
4 posts views Thread by the_init | last post: by
112 posts views Thread by istillshine | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Geralt96 | last post: by
reply views Thread by harlem98 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.