The global statement
François Pinard
pinard at iro.umontreal.ca
Wed Jul 23 13:10:54 EDT 2003
[David Hitillambeau]
> 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. [...] I've read about "The global statement"
> in python's documentation and still can't figure out it's use.
You do not have to use a `global' declaration in global scope, but you ought
to use `global' in local scope whenever you modify that variable in that
scope.
---------------------------------------------------------------------->
# Initialisation has to be done somewhere, not necessarily here.
variable = INITIAL_VALUE
def foo:
# This function looks at `variable', a global, but does not modify it.
# A `global variable' declaration may appear, but is not required.
<instructions>
def bar:
# This function may either look or change `variable', which is global.
global variable
<instructions>
----------------------------------------------------------------------<
The problem with globals is that when can easily abuse them, and have a
program that looks a bit disorganised. I try to avoid them wherever
possible. The usual best way to share data between functions is to use
classes, a bit like this:
---------------------------------------------------------------------->
class Item:
def __init__(self):
self.variable = INITIAL_VALUE
def foo(self):
# Look at or modify self.variable.
<instructions>
def bar(self):
# Look at or modify self.variable.
<instructions>
item = Item()
----------------------------------------------------------------------<
you can then use `item.foo()' or `item.bar()' as needed.
--
François Pinard http://www.iro.umontreal.ca/~pinard
More information about the Python-list
mailing list