[Tutor] UnboundLocal Error

Kent Johnson kent37 at tds.net
Mon Nov 21 00:24:37 CET 2005


Jason Massey wrote:
> I've got a problem with scope that I can't say I've ever encountered.

My guess is that later in setupPlayers() you assign to a variable 'player'. When you do this, every reference to the variable in the function is a local reference. For example:

 >>> x=1
 >>> def bump():
 ...   print x
 ...   x = x + 1
 ...
 >>> bump()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in bump
UnboundLocalError: local variable 'x' referenced before assignment

Because x is assigned in bump(), the x in print x is a local variable and it is not bound a the time of use.

Kent

> 
> The comments explain the situation pretty well.
> 
> 
> import player
> 
> class Game:
> 	def __init__(self,screen):
> 		self.market = Market.Market()
> 		self.countries = pickle.load(open("sup.coords",'r'))
> 		self.deck = deck.Deck()
> 		self.players = {}
> 		print player.Player('foo')     # this line works fine, prints out a
> player instance
> 		self.setupPlayers()               # want to set up all the players so...
> 		
> 		self.screen = screen
> 		
> 	def setupPlayers(self):
> 		print player.Player('bar') # this line fails, with the unbound local error
> 		for super_power in SUPER_POWERS:
> 			self.players[super_power] = player.Player(super_power)
> 			for position,card in enumerate(self.deck):
> 				if card.location in SUPER_POWERS[super_power]:
> 					
> 
> Ouput and traceback:
> 
> <player.Player instance at 0x00AD3F58>
> Traceback (most recent call last):
>   File "C:\Python24\sup.py", line 199, in ?
>     game = Game(screen)
>   File "C:\Python24\sup.py", line 51, in __init__
>     self.setupPlayers()
>   File "C:\Python24\sup.py", line 56, in setupPlayers
>     print player.Player('bar')
> UnboundLocalError: local variable 'player' referenced before assignment
> 
> 
> Something blindingly obvious probably, but I'm at a loss.
> 
> thanks,
> 
> jason
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list