Home > Software design >  Calling a list of methods with next()
Calling a list of methods with next()

Time:07-16

I'd like to call a set of methods in succession -- the same way we use next() to go through an iterable.

The problem is that if I put them in a iter() they are all implicitly called at the same time, and next() does not work as it should.

What am I missing?

Thank you very much!

CodePudding user response:

Is this what you want to achieve? I've edited the original answer to show that it also allows you to pass args to these functions.

def append_num(x):
    x.append(4)
    
def append_other_num(x):
    x.append(5)


func_l = ['append_num', 'append_other_num']

l = [1, 2, 3]
print(l)

for x in func_l:
    eval(x   '(l)')
    print(l)

# Output:
# [1, 2, 3]
# [1, 2, 3, 4]
# [1, 2, 3, 4, 5]

CodePudding user response:

Yes, as I thought, you are saving the results of calls into a list:

f = iter([print("A"), print("B")])

The list will contain two Nones that are the result of calling print() (and btw print("A") is called first and print("B") second, so not at the same time, but before f is created)

What you can do instead is:

funcs = iter([lambda:print("A"), lambda:print("B")])

f = next(funcs)
print('before call')
f()
print('after call')

Output:

before call
A
after call
  • Related