Reputation: 45
Is there a way to access the local variable of a function from a function that is defined within said function? Y is a tuple with strings, and I want whatever caps becomes when a condition is met to stay the same for the next call with the next item in y. I tried to use the built-in function global, but I guess that only works for globals.
def cap_sentence(y):
caps = "on"
def func(x):
if caps == "on"
caps = "off"
return x.capitalize()
elif "." in x:
caps = "on"
return tuple(map(func, y))
Upvotes: 2
Views: 192
Reputation: 151027
Although using nonlocal
is the direct answer to your question, I would encourage you to consider using a callable class here. This avoids re-defining a function every time cap_sentence
is called, and it handles state a more obvious way (to me, anyway). I've taken the liberty of adding a return statement at the end, so that you don't get a string of None
values.
class _CapSentence(object):
def __init__(self):
self.caps = 'on'
def capitalize(self, x):
if self.caps == 'on':
self.caps = 'off'
return x.capitalize()
elif '.' in x:
self.caps = 'on'
return x
def __call__(self, y):
return tuple(map(self.capitalize, y))
cap_sentence = _CapSentence()
print cap_sentence("my feet are cold. my toes are sandwiches.".split())
# output: ('My', 'feet', 'are', 'cold.', 'My', 'toes', 'are', 'sandwiches.')
Upvotes: 0
Reputation: 251001
Use nonlocal
in Python 3.x:
def cap_sentence(y):
caps = "on"
def func(x):
nonlocal caps
if caps == "on":
caps = "off"
return x.capitalize()
elif "." in x:
caps = "on"
return tuple(map(func, y))
In python 2.7:
def cap_sentence(y):
cap_sentence.caps = "on"
def func(x):
if cap_sentence.caps == "on":
cap_sentence.caps = "off"
return x.capitalize()
elif "." in x:
cap_sentence.caps = "on"
return tuple(map(func, y))
Upvotes: 7