If you want functions like abc
and bvc
to use common variables, you generally want to define an object for them to be methods of, like so:
class ActionState(object):
def abc(self, gamestate, depth):
self.alpha = -9999
self.beta = 9999
def bvc(self, gamestate, depth):
self.alpha = -9999
self.beta = 99999
def action(self, gamestate):
state = ActionState()
state.abc(gamestate, 0)
Alternatively, if you really want to, you can enclose a mutable object like a dict around to hold your data:
def action(self, gamestate):
actionstate = { 'alpha': 0, 'beta': 0 }
def abc(gamestate, depth):
actionstate['alpha'] = -9999
actionstate['beta'] = 9999
def bvc(gamestate, depth):
actionstate['alpha'] = -9999
actionstate['beta'] = 9999
abc(gamestate, 0)
Note that the actionstate
parameter isn't passed here -- it's inherited from the enclosing scope. You can pass it explicity instead if you want, in which case abc
and bvc
no longer need to be defined inside of action
. The reason this works and your example doesn't is that Python binds any primitive identifier lexically to the most-local function where it is assigned. So when you assign to alpha
in abc
, Python defines an alpha
as local to abc
, not action
. I believe the only way to get a closure in Python is not to assign to the enclosed variable within the inner function.