Johanna
Johanna

Reputation: 39

Pass a variable that increases as it is called?

How can I do this in python?

a = 0
func(a+=1) # a = 1
func(a+=1) # a = 2

Now I have had to solve it like this:

a = 0
a+=1
func(a)
a+=1
func(a)
...

and there must be a better way, right?

Edit: Actually I also want to be able to pass it to different functions:

a = 0
a+=1
func1(a)
a+=1
func2(a)
a+=1
func1(a)
...

Upvotes: 0

Views: 62

Answers (4)

progmatico
progmatico

Reputation: 4964

There is no way in the sense that in Python, assignment is an instruction, not an operator whose operation returns a value.

You'll have to define a function and either use the global keyword with a or turn a into a mutable. You can also use a decorator for your functions.

a = [0]
#a = 0 # alternative version

def inc(x):
    x[0] += 1
    return x[0]

#    global a # alternative version
#    a += 1
#    return a


def f1(x):
    return x + 1

def f2(x):
    return x + 2


# or (inspired by @jpp comment) decorate your functions
def inc1(x):
    def inner(x):
        x[0] += 1
        return x[0]
    return inner

@inc1
def f3(x):
    return x


for i in range(10):
    print(inc(a))

print()
print(f1(inc(a)))
print(f2(inc(a)))

print()

a = [0]
print(f3(a))
print(f3(a))

Upvotes: 0

Keerthana Prabhakaran
Keerthana Prabhakaran

Reputation: 3787

You can have a wrapping function that calls your function f and simultaneously increment the value of j!

>>> def f(a):print("Value of a is: %d"%a)
...
>>> c=lambda i:(i+1,f(i+1))
>>> j=0
>>> j,_=c(j)
Value of a is: 1
>>> j
1
>>> j,_=c(j)
Value of a is: 2
>>> j
2

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49848

Something simple like this:

a = 0
a+=1;func1(a)
a+=1;func2(a)

Each line is only 2 characters longer than your original request.

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140196

your solution is okay, but if you want to have a counting side effect, use itertools.count object:

import itertools

def f(x):
    print(x)

c = itertools.count()
f(next(c))
f(next(c))

or the variant, performing the next call in the functions themselves (itertools.counter is mutable so you can modify it inside the function):

import itertools

def f(c):
    x = next(c)
    print(x)

c = itertools.count()
f(c)
f(c)

you can initialize it to a non-zero value: c = itertools.count(3)

Upvotes: 3

Related Questions