I am trying to create a script that sets a local variable, references it from a function, and can return the manipulated value back to the main scope (or whatever it\'s call
One approach is to use mutable values, like dicts or lists:
settings = dict(
chambersinreactor = 0,
cardsdiscarded = 0
)
def find_chamber_discard():
settings['chambersinreactor'] += 1
settings['cardsdiscarded'] += 1
find_chamber_discard()
print settings['chambersinreactor']
print settings['cardsdiscarded']
However, if you have a function that is changing some state, you're probably better off wrapping that all up in class, as that's what they're for:
class CardCounter(object):
def __init__(self):
chambersinreactor = 0
cardsdiscarded = 0
def find_chamber_discard(self, hand):
for card in hand:
if card.is_chamber:
self.chambersinreactor += 1
if card.is_discarded:
self.cardsdiscarded += 1
If what you're doing is counting, maybe you could use Counter:
from collections import Counter
def test_for_chamberness(x): return x == 'C'
def test_for_discarded(x): return x == 'D'
def chamber_or_discard(card):
if test_for_chamberness(card):
return 'chambersinreactor'
if test_for_discarded(card):
return 'cardsdiscarded'
hand = ['C','C','D','X','D','E','C']
print Counter(
x for x in (chamber_or_discard(card) for card in hand) if x is not None
)
Personally, I'd go for the class approach, perhaps even wrapping Counter, as it keeps all the associated functionality together.