Global variable declaration

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • psbasha
    Contributor
    • Feb 2007
    • 440

    #1

    Global variable declaration

    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
  • psbasha
    Contributor
    • Feb 2007
    • 440

    #2
    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

    Comment

    • ghostdog74
      Recognized Expert Contributor
      • Apr 2006
      • 511

      #3
      Originally posted by psbasha
      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.

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #4
        Originally posted by psbasha
        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:
        Code:
        #test.py
        # module holds globals
        globalList = []
        globalInt = 5
        
        def printGlobals():
            print globalList
            print globalInt
        
        
        class GlobalModifier:
            def ModifyGlobals(self):
                global globalList
                global globalInt
        
                globalList.append("hello")
                globalInt = 7
        Code:
        # module1.py
        # module1 uses golbal from test.py
        import test
        from test import globalList, globalInt
        globalList.append(0)
        test.printGlobals()
        
        gm = test.GlobalModifier()
        gm.ModifyGlobals()
        
        print globalList, globalInt
        test.printGlobals()
        but not immutable types:
        [0]
        5
        [0, 'hello'] 5
        [0, 'hello']
        7

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          Originally posted by psbasha
          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:
          Code:
          import yourModule
          localVariable = yourModule.globalVariable

          Comment

          • bartonc
            Recognized Expert Expert
            • Sep 2006
            • 6478

            #6
            Originally posted by bartonc
            While I highly recommend AGAINST gobals, mutable types will pass between modules:
            Code:
            #test.py
            # module holds globals
            globalList = []
            globalInt = 5
            
            def printGlobals():
                print globalList
                print globalInt
            
            
            class GlobalModifier:
                def ModifyGlobals(self):
                    global globalList
                    global globalInt
            
                    globalList.append("hello")
                    globalInt = 7
            Code:
            # module1.py
            # module1 uses golbal from test.py
            import test
            from test import globalList, globalInt
            globalList.append(0)
            test.printGlobals()
            
            gm = test.GlobalModifier()
            gm.ModifyGlobals()
            
            print globalList, globalInt
            test.printGlobals()
            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.

            Comment

            • bartonc
              Recognized Expert Expert
              • Sep 2006
              • 6478

              #7
              Originally posted by bartonc
              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:
              Code:
              # test.py
              # class holds globals
              
              import inspect # just for testing this idea
              
              def PrintGlobRep():
                  for member in inspect.getmembers(globRep):
                      if not member[0].startswith('_'):
                          print member
              
              class GlobalRepository:
                  globalList = []
                  globalInt = 5
              
              
              globRep = GlobalRepository()
              # module1.py
              Code:
              # module1 uses Global Repository from test.py
              
              import test # this does initialization of the Global Repository
              from test import globRep # get the class instance
              
              test.PrintGlobRep()
              globRep.newGlobal = 12
              test.PrintGlobRep()
              ('globalInt', 5)
              ('globalList', [])
              ('globalInt', 5)
              ('globalList', [])
              ('newGlobal', 12)

              Comment

              • psbasha
                Contributor
                • Feb 2007
                • 440

                #8
                Code:
                Sample.py
                iVar =1
                
                class Sample1:
                
                    def Func1(self):
                        global iVar
                        iVAr = 20
                        
                        print iVAr
                    
                    def Func2(self):
                        pass
                
                class Sample2:
                
                    def Func3(self):
                        pass
                    
                    def Func4(self):
                        global iVar
                        print iVar
                             
                        print iVar
                        
                
                if __name__ == '__main__':
                    
                    obj1 = Sample1()
                    obj2 = Sample2()
                
                    obj1.Func1()
                    obj2.Func4()
                    print iVar
                >>>
                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

                Comment

                • bartonc
                  Recognized Expert Expert
                  • Sep 2006
                  • 6478

                  #9
                  Originally posted by bartonc
                  The mutable type to use between modules would be a class:
                  Code:
                  # test.py
                  # class holds globals
                  
                  import inspect # just for testing this idea
                  
                  def PrintGlobRep():
                      for member in inspect.getmembers(globRep):
                          if not member[0].startswith('_'):
                              print member
                  
                  class GlobalRepository:
                      globalList = []
                      globalInt = 5
                  
                  
                  globRep = GlobalRepository()
                  # module1.py
                  Code:
                  # module1 uses Global Repository from test.py
                  
                  import test # this does initialization of the Global Repository
                  from test import globRep # get the class instance
                  
                  test.PrintGlobRep()
                  globRep.newGlobal = 12
                  test.PrintGlobRep()
                  ('globalInt', 5)
                  ('globalList', [])
                  ('globalInt', 5)
                  ('globalList', [])
                  ('newGlobal', 12)
                  Class instances can have "global" data by using class variables:
                  Code:
                  # class with shared variables
                  
                  class WithSharedVariables:
                      ## class variables
                      globalList = []
                      globalInt = 5
                  
                      def __init__(self):
                          self.localInt = 11
                  
                      def printClassVars(self):
                          print WithSharedVariables.globalList
                          print WithSharedVariables.globalInt
                  
                      def IncGlobalInt(self):
                          WithSharedVariables.globalInt += 1
                  
                      def AppendGlobalList(self, item):
                          WithSharedVariables.globalList.append(item)
                  
                  
                  
                  wsv1 = WithSharedVariables()
                  wsv2 = WithSharedVariables()
                  
                  wsv2.IncGlobalInt()
                  wsv1.AppendGlobalList("hello")
                  
                  wsv2.printClassVars()

                  Comment

                  • bartonc
                    Recognized Expert Expert
                    • Sep 2006
                    • 6478

                    #10
                    Originally posted by psbasha
                    Code:
                    Sample.py
                    iVar =1
                    
                    class Sample1:
                    
                        def Func1(self):
                            global iVar
                            iVAr = 20
                            
                            print iVAr
                        
                        def Func2(self):
                            pass
                    
                    class Sample2:
                    
                        def Func3(self):
                            pass
                        
                        def Func4(self):
                            global iVar
                            print iVar
                                 
                            print iVar
                            
                    
                    if __name__ == '__main__':
                        
                        obj1 = Sample1()
                        obj2 = Sample2()
                    
                        obj1.Func1()
                        obj2.Func4()
                        print iVar
                    >>>
                    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:
                    Code:
                    iVar =1
                    
                    class Sample1:
                    
                        def Func1(self):
                            global iVar
                            iVAr = 20

                    Comment

                    • psbasha
                      Contributor
                      • Feb 2007
                      • 440

                      #11
                      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

                      Comment

                      • bartonc
                        Recognized Expert Expert
                        • Sep 2006
                        • 6478

                        #12
                        Originally posted by psbasha
                        Code:
                        Sample.py
                        iVar =1
                        
                        class Sample1:
                        
                            def Func1(self):
                                global iVar
                                iVAr = 20
                                
                                print iVAr
                            
                            def Func2(self):
                                pass
                        
                        class Sample2:
                        
                            def Func3(self):
                                pass
                            
                            def Func4(self):
                                global iVar
                                print iVar
                                     
                                print iVar
                                
                        
                        if __name__ == '__main__':
                            
                            obj1 = Sample1()
                            obj2 = Sample2()
                        
                            obj1.Func1()
                            obj2.Func4()
                            print iVar
                        >>>
                        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.

                        Comment

                        • psbasha
                          Contributor
                          • Feb 2007
                          • 440

                          #13
                          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

                          Comment

                          • bartonc
                            Recognized Expert Expert
                            • Sep 2006
                            • 6478

                            #14
                            Originally posted by psbasha
                            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?

                            Comment

                            • psbasha
                              Contributor
                              • Feb 2007
                              • 440

                              #15
                              Code:
                              Sample1.py
                              class CSample1:
                              
                                  def Func1(self):
                                      global iVar
                                      iVar = 20
                                      
                                      print iVar
                                  
                                  def Func2(self):
                                      pass
                              Code:
                              Sample2.py
                              
                              class CSample2:
                              
                                  def Func3(self):
                                      pass
                                  
                                  def Func4(self):
                                      global iVar
                                      print iVar
                              Code:
                              Main.py
                              
                              from Sample1 import CSample1
                              from Sample2 import CSample2
                              
                              if __name__ == '__main__':
                                
                                  
                                  obj1 = CSample1()
                                  obj2 = CSample2()
                              
                                  obj1.Func1()
                                  obj2.Func4()
                                  print iVar
                              I am getting the following error

                              Traceback (most recent call last):
                              File "C:\Python24\Li b\site-packages\python win\pywin\frame work\scriptutil s.py", line 307, in RunScript
                              debugger.run(co deObject, __main__.__dict __, start_stepping= 0)
                              File "C:\Python24\Li b\site-packages\python win\pywin\debug ger\__init__.py ", line 60, in run
                              _GetCurrentDebu gger().run(cmd, globals,locals, start_stepping)
                              File "C:\Python24\Li b\site-packages\python win\pywin\debug ger\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
                              >>>

                              Comment

                              Working...