[Tutor] modifying global within function without declaring global

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Jan 9 02:32:29 CET 2013


On 9 January 2013 01:07, Alan Gauld <alan.gauld at btinternet.com> 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.

I agree entirely with what Alan said but have a slightly different way
of thinking about it: you only need the global statement if you want
to assign directly to a name (and have the assignment apply globally).
Examples:

x = some_obj()

def some_function():
    x = b    # direct assignment (global statement needed)

def some_other_function():
    x.e = c    # attribute assignment (global not needed)
    x[f] = d    # item assignment (global not needed)
    x.mutating_func(g)     # method call (global not needed)

The only one of the above statements that is affected by a "global x"
statement is the first. The other three calls will all modify x in
place regardless of any global statement. A global statement is needed
when you want to assign directly to a variable name and have the
assignment apply in an outer scope as is the case with the "x = b"
line above. In any other situation the global statement does nothing.


Oscar


More information about the Tutor mailing list