The global statement

Discussion in 'Python' started by David Hitillambeau, Jul 23, 2003.

  1. 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, Jul 23, 2003
    #1
    1. Advertising

  2. On Wed, 23 Jul 2003 16:56:08 +0200, Thomas Güttler wrote:

    > If foo and bar are in the same file,
    > you don't need the "global".


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

    Thanks for your reply.
    --
    David.H
    David Hitillambeau, Jul 23, 2003
    #2
    1. Advertising

  3. David Hitillambeau

    Peter Hansen Guest

    Thomas Güttler wrote:
    >
    > global BAD
    > BAD=1
    >
    > def foo():
    > global BAD
    > print BAD


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

    -Peter
    Peter Hansen, Jul 23, 2003
    #3
  4. David Hitillambeau

    Duncan Booth Guest

    "David Hitillambeau" <> wrote in
    news:p:

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

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

    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
    int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
    "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
    Duncan Booth, Jul 23, 2003
    #4
  5. Thomas Güttler fed this fish to the penguins on Wednesday 23 July 2003
    07:56 am:

    > David Hitillambeau wrote:
    >> read and write access over it.

    >
    > If foo and bar are in the same file,
    > you don't need the "global".
    >

    He does for the "write access"...

    --
    > ============================================================== <
    > | Wulfraed Dennis Lee Bieber KD6MOG <
    > | Bestiaria Support Staff <
    > ============================================================== <
    > Bestiaria Home Page: http://www.beastie.dm.net/ <
    > Home Page: http://www.dm.net/~wulfraed/ <
    Dennis Lee Bieber, Jul 23, 2003
    #5
  6. On Wed, 23 Jul 2003 16:56:08 +0200, Thomas =?ISO-8859-15?Q?G=FCttler?= <> wrote:

    >David Hitillambeau wrote:
    >
    >> 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.

    >
    >Hi David,
    >
    >global BAD

    Don't need the above line if you are already in global scope.
    >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".
    >

    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:

    >>> BAD = 'global BAD'
    >>> def baz():

    ... BAD = 'local assignment binds locally unless global is specified'
    ... print BAD
    ...
    >>> baz()

    local assignment binds locally unless global is specified
    >>> print BAD

    global BAD



    >>> def baz():

    ... global BAD
    ... BAD = 'assigned locally, but destination global instead because of "global BAD"'
    ... print BAD
    ...
    >>> print BAD

    global BAD
    >>> baz()

    assigned locally, but destination global instead because of "global BAD"
    >>> print BAD

    assigned locally, but destination global instead because of "global BAD"



    >>> BAD = 'global BAD'
    >>> def baz(BAD=BAD):

    ... BAD += ' -- local mod to local arg pre-bound to global BAD when baz defined'
    ... print BAD
    ...
    >>> print BAD

    global BAD
    >>> BAD = 'changed global'
    >>> print BAD

    changed global
    >>> baz()

    global BAD -- local mod to local arg pre-bound to global BAD when baz defined
    >>> print BAD

    changed global

    HTH

    Regards,
    Bengt Richter
    Bengt Richter, Jul 23, 2003
    #6
  7. David Hitillambeau

    Andy Jewell Guest

    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 variable at
    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 (notwithstanding
    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_global():
    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
    Andy Jewell, Jul 23, 2003
    #7
  8. David Hitillambeau

    Duncan Booth Guest

    Andy Jewell <> wrote in
    news::

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


    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
    int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
    "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
    Duncan Booth, Jul 24, 2003
    #8
  9. David Hitillambeau

    Nick Vargish Guest

    "David Hitillambeau" <> writes:

    > 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.


    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!=obwAcboefstobudi/psh?')
    Nick Vargish, Jul 25, 2003
    #9
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    3
    Views:
    800
  2. Jay McGavren
    Replies:
    11
    Views:
    1,127
    Alan Krueger
    Jan 16, 2006
  3. tedsuzman
    Replies:
    2
    Views:
    7,076
    Michel Claveau, résurectionné d'outre-bombe inform
    Jul 21, 2004
  4. Ted
    Replies:
    1
    Views:
    460
    Duncan Booth
    Jul 22, 2004
  5. Replies:
    21
    Views:
    1,050
    Giannis Papadopoulos
    Aug 2, 2005
Loading...

Share This Page