Skip to content Skip to sidebar Skip to footer

How To Use Local Variable In A Function And Return It?

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 called; I'm

Solution 1:

Functions shouldn't have to know what scope they're called from; the point of a function is to make a re-usable block of code that can be invoked multiple times from different places.

You communicate information to a function by passing it through its input variables. The function communicates information back to its caller by returning it.

Managing the variables of a scope is the job of the code in that scope not any functions it invokes. If you need to set variables to values determined by a function, then you have the function return those values and you use them to set the variables. If the values the function is calculating depend on the values of variables you have in the calling scope, then you need to pass them to the function as arguments. The function you're calling shouldn't have to know what variables you're using, and shouldn't be able to mess with them.

Putting that all together, what you want to do is something like this:

deffind_chamber_discard(chambersinreactor, cardsdiscarded):
    chambersinreactor += 1
    cardsdiscarded += 1return (chambersinreactor, cardsdiscarded)

chambersinreactor = 0;
cardsdiscarded = 0;

chambersinreactor, cardsdiscarded = find_chamber_discard(chambersinreactor, cardsdiscarded)

print chambersinreactor
print cardsdiscarded

There are ways to get around this with global variables or manipulating mutable data structures, but ultimately they make your program less flexible and more likely to contain errors that will be difficult to spot. There is a place for those techniques, but the first method you reach for to communicate information to and from functions really should be passing arguments and receiving return values.

Solution 2:

One approach is to use mutable values, like dicts or lists:

settings = dict(
    chambersinreactor = 0,
    cardsdiscarded = 0
)

deffind_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:

classCardCounter(object):def__init__(self):
        chambersinreactor = 0
        cardsdiscarded = 0deffind_chamber_discard(self, hand):
        for card inhand:if card.is_chamber:self.chambersinreactor += 1if card.is_discarded:self.cardsdiscarded += 1

If what you're doing is counting, maybe you could use Counter:

from collections import Counter

deftest_for_chamberness(x): return x == 'C'deftest_for_discarded(x): return x == 'D'defchamber_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 isnotNone
)

Personally, I'd go for the class approach, perhaps even wrapping Counter, as it keeps all the associated functionality together.

Solution 3:

#!/usr/bin/env python
chambersinreactor = 0; cardsdiscarded = 0;

deffind_chamber_discard():
    chambersinreactor = 0
    cardsdiscarded = 0
    chambersinreactor += 1 
    cardsdiscarded += 1return(chambersinreactor, cardsdiscarded)

#Here the globals remain unchanged by the locals.#In python, a scope is similar to a 'namespace'
find_chamber_discard()

print chambersinreactor #prints as 0print cardsdiscarded 

#I've modified the function to return a pair (tuple) of numbers.#Above I ignored them. Now I'm going to assign the variables in the #main name space to the result of the function call.print("=====with assignment===")
(chambersinreactor, cardsdiscarded) = find_chamber_discard()

print chambersinreactor #  now prints as 1print cardsdiscarded 

# Here is another way that doesn't depend on returning values.#Pass a dictionary of all the main variables into your function#and directly access them from within the function as neededprint("=======using locals===")
deffind_chamber_discard2(_locals):
    _locals['chambersinreactor'] += 1
    _locals['cardsdiscarded'] += 1return

find_chamber_discard2(locals())

print chambersinreactor #incremented the value, which was already 1print cardsdiscarded 

Post a Comment for "How To Use Local Variable In A Function And Return It?"