tags:

views:

396

answers:

2

I have this code here. The only part I can add code to is in main_____ AFTER the 'i=1' line. This script will be executing multiple times and will have some variable (might not be 'i', could be 'xy', 'var', anything), incrementing by 1 each time. I have gotten this to work by declaring 'i' as global above the method, but unfortunately, I can't keep it that way.

Is there a way in which I can make 'i' function as a global variable within the above-mentioned parameters?

def main______():
    try:
        i+=1
    except NameError:
        i=1 
main______()
+1  A: 

If you want to use a global variable you have to declare it as global. What's wrong with that?

If you need to store state between calls, you should be using a class

>>> class F():
...     def __init__(self):
...         self.i=0
...     def __call__(self):
...         print self.i
...         self.i+=1
... 
>>> f=F()
>>> f()
0
>>> f()
1
>>> f()
2
gnibbler
+1 the first one. Second one should go into a shredding machine.
Ali A
-1: The hacky way is dangerously close to a bug. Using mutable objects as default values is so dangerous that showing it here is trouble waiting to happen. Even if it is correct. It's still a bad thing.
S.Lott
Due to popular demand, I've shredded the hacky way.
gnibbler
A: 

You could try using a generator

>>> def main(i):
...     while True:
...             i += 1
...             yield i
...
>>> x = main(5)
>>> x.next()
6
>>> x.next()
7
chris
`itertools.count()` does exactly that except it yields before the increment, so the first `x.next()` returns `5`
gnibbler