The global statement

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • David Hitillambeau

    The global statement

    Hi guys,
    As I am new to Python, i was wondering how to declare and use global
    variables. Suppose i have the following structure in the same module (same
    file):

    def foo:
    <instructions >
    <instructions >
    def bar:
    <instructions >
    <instructions >

    I want to enable some sharing between the two functions (foo and bar)
    using one global variable in such a way that each function can have read
    and write access over it.

    How can i manage this please?

    I've read about "The global statement" in python's documentation and still
    can't figure out it's use.

    Thanks.
    --
    David.H
  • David Hitillambeau

    #2
    Re: The global statement

    On Wed, 23 Jul 2003 16:56:08 +0200, Thomas Güttler wrote:
    [color=blue]
    > If foo and bar are in the same file,
    > you don't need the "global".[/color]

    Then when is "global" required? What is it's role?

    Thanks for your reply.
    --
    David.H

    Comment

    • Peter Hansen

      #3
      Re: The global statement

      Thomas Güttler wrote:[color=blue]
      >
      > global BAD
      > BAD=1
      >
      > def foo():
      > global BAD
      > print BAD[/color]

      Note: the first use of global above, outside a function, is redundant.

      -Peter

      Comment

      • Duncan Booth

        #4
        Re: The global statement

        "David Hitillambeau" <edavid@intnet. mu> wrote in
        news:pan.2003.0 7.23.15.14.52.4 [email protected] :
        [color=blue]
        > On Wed, 23 Jul 2003 16:56:08 +0200, Thomas Güttler wrote:
        >[color=green]
        >> If foo and bar are in the same file,
        >> you don't need the "global".[/color]
        >
        > Then when is "global" required? What is it's role?
        >[/color]
        I'm afraid Thomas Güttler's answer was a bit misleading.

        You never need to use the 'global' statement outside a function. The only
        effect of 'global' is to declare that a variable assigned to within a
        function is actually a global variable. The fact that it is a global
        variable lasts only for the duration of the function in which it occurs.

        Global variables are not in fact global. They are global only to the module
        in which they occur (usually you get one module per source file, although
        be aware that if you run a script A.py, it runs in the module __main__ and
        importing A will give you a second module from the same source, with its
        own global variables).

        If you want to access a global variable from another module you don't need
        a global statement, just prefix the variable with a reference to the
        module. e.g. 'A.x' will access the global 'x' in module 'A'.

        So:

        BAD=1

        def foo():
        global BAD
        BAD = 2

        def bar():
        BAD = 3
        global BAD

        def xyzzy():
        BAD="xyzzy"

        def plugh():
        print "BAD is",BAD

        Outside the function assigning to BAD makes it a global variable. Inside
        foo and bar the global statement makes BAD a global variable for the
        assignment, notice that it doesn't matter where in the function the global
        statement occurs, although it is conventional to list globals at the head
        of the function.

        'xyzzy' simply sets a local variable with the same name as the global.

        'plugh' accesses the global: if you don't try to assign to it you don't
        need to tell Python its a global.

        Finally, all of this confusion can be avoided if you use classes instead of
        global variables. e.g.

        class MyClass:
        def __init__(self):
        self.value = 0

        def foo(self):
        self.value = 1

        def bar(self):
        self.value = 2

        obj = MyClass()
        obj.foo()
        obj.bar()

        --
        Duncan Booth [email protected] k
        int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
        "\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?

        Comment

        • Dennis Lee Bieber

          #5
          Re: The global statement

          Thomas Güttler fed this fish to the penguins on Wednesday 23 July 2003
          07:56 am:
          [color=blue]
          > David Hitillambeau wrote:[color=green]
          >> read and write access over it.[/color]
          >
          > If foo and bar are in the same file,
          > you don't need the "global".
          >[/color]
          He does for the "write access"...

          --[color=blue]
          > =============== =============== =============== =============== == <
          > [email protected] om.com | Wulfraed Dennis Lee Bieber KD6MOG <
          > [email protected] | Bestiaria Support Staff <
          > =============== =============== =============== =============== == <
          > Bestiaria Home Page: http://www.beastie.dm.net/ <
          > Home Page: http://www.dm.net/~wulfraed/ <[/color]

          Comment

          • Bengt Richter

            #6
            Re: The global statement

            On Wed, 23 Jul 2003 16:56:08 +0200, Thomas =?ISO-8859-15?Q?G=FCttler? = <guettler@thoma s-guettler.de> wrote:
            [color=blue]
            >David Hitillambeau wrote:
            >[color=green]
            >> Hi guys,
            >> As I am new to Python, i was wondering how to declare and use global
            >> variables. Suppose i have the following structure in the same module (same
            >> file):
            >>
            >> def foo:
            >> <instructions >
            >> <instructions >
            >> def bar:
            >> <instructions >
            >> <instructions >
            >>
            >> I want to enable some sharing between the two functions (foo and bar)
            >> using one global variable in such a way that each function can have read
            >> and write access over it.[/color]
            >
            >Hi David,
            >
            >global BAD[/color]
            Don't need the above line if you are already in global scope.[color=blue]
            >BAD=1
            >
            >def foo():
            > global BAD
            > print BAD
            >
            >def bar():
            > global BAD
            > print BAD
            >
            >foo()
            >bar()
            >
            >If foo and bar are in the same file,
            >you don't need the "global".
            >[/color]
            Unless you want to rebind it. Then you need it in order not
            to get the default behaviour of creating a local within the function.
            E.g., here are some variations to think about. Note what gets changed and when:
            [color=blue][color=green][color=darkred]
            >>> BAD = 'global BAD'
            >>> def baz():[/color][/color][/color]
            ... BAD = 'local assignment binds locally unless global is specified'
            ... print BAD
            ...[color=blue][color=green][color=darkred]
            >>> baz()[/color][/color][/color]
            local assignment binds locally unless global is specified[color=blue][color=green][color=darkred]
            >>> print BAD[/color][/color][/color]
            global BAD


            [color=blue][color=green][color=darkred]
            >>> def baz():[/color][/color][/color]
            ... global BAD
            ... BAD = 'assigned locally, but destination global instead because of "global BAD"'
            ... print BAD
            ...[color=blue][color=green][color=darkred]
            >>> print BAD[/color][/color][/color]
            global BAD[color=blue][color=green][color=darkred]
            >>> baz()[/color][/color][/color]
            assigned locally, but destination global instead because of "global BAD"[color=blue][color=green][color=darkred]
            >>> print BAD[/color][/color][/color]
            assigned locally, but destination global instead because of "global BAD"


            [color=blue][color=green][color=darkred]
            >>> BAD = 'global BAD'
            >>> def baz(BAD=BAD):[/color][/color][/color]
            ... BAD += ' -- local mod to local arg pre-bound to global BAD when baz defined'
            ... print BAD
            ...[color=blue][color=green][color=darkred]
            >>> print BAD[/color][/color][/color]
            global BAD[color=blue][color=green][color=darkred]
            >>> BAD = 'changed global'
            >>> print BAD[/color][/color][/color]
            changed global[color=blue][color=green][color=darkred]
            >>> baz()[/color][/color][/color]
            global BAD -- local mod to local arg pre-bound to global BAD when baz defined[color=blue][color=green][color=darkred]
            >>> print BAD[/color][/color][/color]
            changed global

            HTH

            Regards,
            Bengt Richter

            Comment

            • Andy Jewell

              #7
              Re: The global statement

              Gentlepeople,

              I found it easier to envisage the Python global statement as the inverse of
              the Pascal/Modula/C concept:

              In traditional (compiled procedural) languages, one *declares* a variableat
              the 'top-level' scope, and then uses it as one would a local variable in
              functions/procedures, but without declaring it again. Global variables in
              these types of languages are treated differently in most respects (where they
              are stored for example: heap rather than stack, usually). There is usually
              no special notation, however, to enable the reader (especially one not
              skilled in the language at hand) to determine that a given variable is, in
              fact, global or local: you have to know the scoping rules of the language.
              If you define a variable outside of a function, it's global (notwithstandin g
              the placement/sequencing rules for that language).

              Python is different (as always). It allows you to *read* the value (pardon
              the over-simplification) of variables declared at the 'top level', that is,
              created outside of a function, but you can't *write* to it without first
              telling Python that you wish to do so (by using the global statement):
              forgetting to do so results in the creation of a similarly named local
              variable, with no relation whatsoever to the intended global variable. I tend
              to think of it as 'telling python it's ok to change' the variable.


              pascal;

              var a_global: integer;

              function read_a_global;
              begin
              read_a_global:= a_global; (* return the value of global variable *)
              end;

              procedure modify_a_global ;
              begin
              a_global:=10; (* modify global variable *)
              end;

              end.


              #python:
              a_global=1

              def read_a_global() :
              return a_global # REFERENCE the global variable

              def cant_modify_a_g lobal():
              a_global = 10 # makes a local variable called a_global
              # which disappears after this point:

              def modify_a_global (n):
              global a_global # Makes a_global locally accessible for modifying
              a_global = 10 # top-level a_global variable is modified



              When I first tried to do this sort of thing in python, i wrote:

              global a_global

              def modify_a_global ():
              a_global=10

              ...and wondered why it didn't work. I admit that the docs didn't really help
              much either, as they don't tell you to put the statement *inside* the
              function that needs to modify the variable! I only finally understood by
              reading some of the standard library code, after searching it for the word
              'global' itself!

              just my 2p...

              hope that helps

              -andyj

              Comment

              • Duncan Booth

                #8
                Re: The global statement

                Andy Jewell <[email protected]> wrote in
                news:mailman.10 58999017.16056. [email protected] :
                [color=blue]
                > I found it easier to envisage the Python global statement as the
                > inverse of the Pascal/Modula/C concept:[/color]

                Indeed, Pascal/Modula/C say "here's a variable, use it anywhere! Program
                structure? Who needs it?". Python, OTOH, requires you to say near the point
                of use "I am going to break the rules of good program design, but just for
                this function."

                In some ways this is analagous to the COMEFROM statement (see
                http://www.fortran.com/fortran/come_from.html). Just not very.

                --
                Duncan Booth [email protected] k
                int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
                "\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?

                Comment

                • Nick Vargish

                  #9
                  Re: The global statement

                  "David Hitillambeau" <edavid@intnet. mu> writes:
                  [color=blue]
                  > I want to enable some sharing between the two functions (foo and bar)
                  > using one global variable in such a way that each function can have read
                  > and write access over it.[/color]

                  Using the "global" statement seems unpythonic to me, for reasons I'm
                  too lazy to come up with good ways to express. :^) This is what I do,
                  if I need something like this:

                  -----------------------------
                  class Global:
                  """Generic container for shared variables."""
                  pass

                  def foo():
                  Global.somevar = 'set in foo'

                  def bar():
                  print Global.somevar

                  foo()
                  bar()
                  -----------------------------

                  HTH,

                  Nick

                  --
                  # sigmask || 0.2 || 20030107 || public domain || feed this to a python
                  print reduce(lambda x,y:x+chr(ord(y )-1),' Ojdl!Wbshjti!=o bwAcboefstobudi/psh?')

                  Comment

                  Working...