[Tutor] modifying global within function without declaring global

Nathaniel Huston nathanielhuston at yahoo.com
Sat Jan 5 02:27:56 CET 2013


As far as I understood, this shouldn't be possible. this is python 2.7


weirdness is in deal() at the end


################################################


import random

class card:
    def __init__(self, suit, rank, name):
        self.suit = suit
        self.rank = rank
        self.name = name
        

def makedeck():
    #creates an ordered deck of card objects
    #ranks are clumped (four 2's, four 3's etc)
    
    suits = ['Spades', 'Diamonds', 'Clubs', 'Hearts']
    ranks = []
    for x in range(2, 15):
        ranks.append(x)

    names = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace']

    stack = []

    for rank in ranks:
        for suit in suits:
            name = names[rank - 2]
            stack.append(card(suit, rank, name))

    return stack


def deal(quantity):
    
    hand = []
    for cards in range(0, quantity):
        hand.append(deck.pop())
    return hand

#################################################

#if you run this and do:

deck = makedeck()
hand = deal(5)

#and then finally

len(deck)

#we find that the global deck has been modified within the deal() function without including

global deck

#within the deal() function

#it seems insane to me that it's possible to alter global variables within functions without declaring global or passing the variable in as an argument.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130104/4fe11dd3/attachment.html>


More information about the Tutor mailing list