[Tutor] modifying global within function without declaring global
Mitya Sirenef
msirenef at lightbird.net
Wed Jan 9 02:32:40 CET 2013
On Tue 08 Jan 2013 08:07:57 PM EST, Alan Gauld wrote:
> On 05/01/13 01:27, Nathaniel Huston wrote:
>
>> def deal(quantity):
>>
>> hand = []
>> for cards in range(0, quantity):
>> hand.append(deck.pop())
>> return hand
>
> > #we find that the global deck has been modified within the deal()
> > function without including
> >
> > global deck
> >
> > #within the deal() function
>
> Notice deal() modifies the contents of deck but not deck itself - it
> still points to the same list object.
>
> You only need to use global if you are changing the value. Since you
> are only modifying the contents you don't need the global statement.
>
> You have to think in terms of objects and names as references to the
> objects. If you are changing the object that the name refers to you
> need to use global. If you are only changing the content of the object
> then there is no need for global. The object here is the list.
>
Actually, modifying a global name is OK, it is not OK to rebind it,
e.g.:
# OK:
l=[]
def f(): l.append(1)
# won't rebind global:
def b(): l=[2]
After you run both, you'll see l is [1]
This is a very important difference, if it helps, it's similar to this
real-world example:
Let's say you're a student in a school and
you have a teacher who is standing before a blackboard and
writing something. After he gets to the end of the blackboard,
he picks up a phone and says "supply room? Can you please
order a new blackboard and deliver to me, I've run out of
space". Then a few minutes go by and a delivery person
shows up, with a spanking new black board, installs it
and then leaves.
The teacher goes back to writing down his formulas but
soon runs out of space again and has to call for a new
board again.
Someone raises a hand and asks him why he does not
erase the board, instead. He looks puzzled and replies
that he thought it's the same thing, whether you erase
the board or make a new one.
In Python, of course, both operations are equally fast
(more or less), so it's easy to forget about the difference.
# order new board
board = []
# OR
board = list()
# erase the existing board
board[:] = []
So, back to local and global bindings... If the board is
not a global name, you CAN modify it, but you can NOT
order a new board and have it available globally --
unless you use the 'global' keyword.
Integers, floats and strings are immutable so you can't
modify them anyway, when you change them, you can
only rebind:
# global is NOT changed!
x = 5
def f(): x = 6
Hope this helps, -m
--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
More information about the Tutor
mailing list