4

is it possible to store a variable from a while loop to a function and then call that same variable from the function at the end of the loop

for eg:during while loop, problem here is that when i try to retrieve the variable from store() it fails...as it needs arguments to be passed..

def store(a,b,c):
    x1 = a
    y1 = b
    z1 = c
    return (x1,y1,z1)

def main():
    while condition:
          x = .......
          y = .......
          z = .......
          ......
          ......
          store(x,y,z) #store to function...
          ......
          ......
          ......
          s1,s2,s3 = store()
          ......
          ......
          ......
Raymond
  • 31
  • 7
krisdigitx
  • 7,068
  • 20
  • 61
  • 97
  • 1
    -1: This makes essentially no sense at all. `store=x,y,z` and `s1,s2,s3=store` work perfectly. Why mess with more complex function syntax? – S.Lott Aug 02 '11 at 10:48
  • you want static variables in a function? – warvariuc Aug 02 '11 at 11:47
  • @S.Lott sometimes, creating a proper MRE means taking out calculation that justifies the approach. The goal here is to learn something about functions, so the fact that the function as written is useless, should not detract from the question. The function in the example *should be* useless, in order to avoid answers specific to the contents. That said, years later I have established a better canonical for this sort of problem (which actually was asked earlier than this one, and thus could have been used at the time). – Karl Knechtel Oct 13 '22 at 18:52

5 Answers5

12

Technically speaking, if you had a deep, burning desire to do this with functions, you can always do it with a closure (which is, as we all know, a poor man's object):

def store(a,b,c):
    def closure():
        return (a,b,c)
    return closure

stored = store(1,2,3)
print stored()

prints in (1,2,3)

Nate
  • 12,499
  • 5
  • 45
  • 60
10

As others have stated, there is probably a more suitable choice than this, but it might be convenient in some situations (perhaps in a REPL). Here's a simple function that does what you want with any number of values.

def store(*values):
    store.values = values or store.values
    return store.values
store.values = ()

Example

>>> store(1, 2, 3)
>>> a, b, c = store()
>>> print a, b, c
1 2 3
>>> store(4, 5)
>>> a, b = store()
>>> print a, b
4 5
Jeremy
  • 1
  • 85
  • 340
  • 366
7

Hmmm, unless I am misunderstanding, this is a classic non-solution to a non-problem.

Why not just use the language as it is?

while condition:

   x = something
   y = else
   z = altogether
   ...
   save_state = (x,y,z)   ## this is just a python tuple.
   ...
   # do something else to x, y and z, I assume
   ...
   x, y, z = save_state

Depending on the type of x, y and z you may have to be careful to store a copy into the tuple.

(Also, your indentation is wrong, and there is no such thing as end in python.)

Update: Ok, if I understand better, the question is just to be able to use the previous value the next time through. In the simplest case, there is no problem at all: the next time through a loop, the the value of x,y, and z are whatever they were at the end of the previous time through the loop (this is the way all programming languages work).

But if you want to be explicit, try something like this:

 x_prev = some_starting_value
 x = some_starting_value
 while condition:
      x = something_funky(x_prev)

      .... other stuff ....

      x_prev = x

(but again, note that you don't need x_prev at all here: x=something_funky(x) will work.)

Andrew Jaffe
  • 26,554
  • 4
  • 50
  • 59
  • what i wanted was that it should store the previous state when the loops runs, so "x,y,z = save_state" will have the value of x,y,z during the previous loop... – krisdigitx Aug 02 '11 at 10:21
  • @krisdigitx: "what i wanted was that it should store the previous state"? What? Please **update** your question to be **very specific** on what you want. Your question does not show that as a requirement. Please **Fix** the question. – S.Lott Aug 02 '11 at 10:42
  • i meant when the loop runs x,y and z get new values constantly, i want to store the value of x,y,z and call them when the loop runs next time...hope you understand now.. – krisdigitx Aug 02 '11 at 11:06
  • @krisdigitx: I (still) don't understand. What do you mean 'runs next time'? Do you just want the value during the previous iteration? If so, this is easy (but nothing particularly to do with python: at the beginning of the loop, `x,y,z` already have the values from the previous iteration (except the first time through). – Andrew Jaffe Aug 02 '11 at 16:10
3

As much as this is a bad idea I like applying weird solutions so here

class Store(object):
    def __init__(self, f):
        self.f = f
        self.store = None

    def __call__(self, *args):
        self.store = self.f(*args)

@Store        
def test(a,b,c):
    return a+b+c

print test(1,2,3)
print test.store

Decorate the function with Store then call function.store to get what you called in it, if the function is never called it returns a single None, you could make it raise an exception but personally I didn't want to.

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
1

No, you can't do this.

Also, it's a terrible, terrible idea. "Store to a function" is such an awful and wrong thing to do that I hesitate to provide working code.

Use a callable object.

class Store( object ):
    def __init__( self ):
        self.x, self.y, self.z = None, None, None
    def __call__( self, x=None, y=None, z=None ):
        if x is None and y is None and z is None:
            return self.x, self.y, self.z
        else:
            self.x, self.y, self.z = x, y, z

What's better is to do something simpler that doesn't involve a function with magical properties that does two different things when called with and without arguments.

Anything is better than "store to a function". Anything.

Really.

Anything.

S.Lott
  • 384,516
  • 81
  • 508
  • 779