CodeHard_or_HardCode
CodeHard_or_HardCode

Reputation: 287

Is there a way to append a function with arguments into a list?

I have created a loop that runs functions out of a list.

At the end of each function I run, I append the next function that I would need to run into this list.

This is how I append them into the list:

self.FunctionBuffer["stack"].append( self.ApplyFunction )

This is how I call them:

if len(self.FunctionBuffer["stack"]) > 0:
    self.FunctionBuffer["stack"][0]()

Everything had been working well except now I want to add arguments to the functions I append and there doesn't seem to be a syntax for this such as:

self.FunctionBuffer["stack"].append( self.ApplyFunction(arg1, arg2, arg3) )

Is there a way I can append a function with arguments into a list?

Upvotes: 1

Views: 2309

Answers (2)

ali_m
ali_m

Reputation: 74222

Why not just shove a list containing your arguments into the second element of the list you're appending to FunctionBuffer?

self.FunctionBuffer["stack"].append([self.ApplyFunction,[arg1, arg2, arg3]])

...

if len(self.FunctionBuffer["stack"]) > 0:
    self.FunctionBuffer["stack"][0][0](*self.FunctionBuffer["stack"][0][1])

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123530

Yes, use functools.partial() to create a new callable that'll call your function with arguments:

from functools import partial

self.FunctionBuffer["stack"].append(partial(self.ApplyFunction, arg1, arg2, arg3))

functools.partial stores your function and your arguments, and when you call the partial object returned, it in turn will invoke the function with those arguments. You can add extra arguments when calling that object too:

>>> from functools import partial
>>> def foo(bar, baz): print (bar, baz)
... 
>>> p = partial(foo, 1, 2)
>>> p()
(1, 2)
>>> p = partial(foo, 1)
>>> p(2)
(1, 2)

You can achieve the same thing with lambdas:

self.FunctionBuffer["stack"].append(lambda: self.ApplyFunction(arg1, arg2, arg3))

but a partial() is faster and provides the option to pass in more arguments.

Upvotes: 3

Related Questions