Python store function in variable with arguments

By far easiest is just to use lambda in place

self.option1 = Button(frame, text="1842", 
    command=lambda: self.checkAnswer(question=3, answer=2))

Though, in a similar but a bit more complicated cases, you really should use a function factory such as

def answerCheckerFactory(self, question, answer):
    def checker():
        return self.checkAnswer(question, answer)

    return checker

    ...
    self.option1 = Button(frame, text="1842", 
        command=self.answerCheckerFactory(question=3, answer=2))

because it would make sure that you pass in correct arguments (not quetsion (sic) for example); notice the difference from functools.partial which allows you to mistype the function arguments and get an exception only when clicked on the button ;)

Also, hardcoding the questions / answers in the button code does not seem right...

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In this article, we are going to see how to assign a function to a variable in Python. In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. 

    Implementation

    Simply assign a function to the desired variable but without () i.e. just with the name of the function. If the variable is assigned with function along with the brackets (), None will be returned.

    Syntax:

    def func():
    {
    ..
    }
    
    var=func
    
    var()
    var()

    Example:

    Python3

    def a():

      print("GFG")

    var=a

    var()

    Output: 

    GFG

    The following programs will help you understand better:

    Example 1: 

    Python3

    x = 123

    def sum():

        x = 98

        print(x)

        print(globals()['x'])

    print(x)

    z = sum

    z()

    z()

    Output:

    123
    98
    123
    98
    123

    Example 2: parameterized function

    Python3

    def even_num(a):

        if a % 2 == 0:

            print("even number")

        else:

            print("odd number")

    z = even_num

    z(67)

    z(10)

    z(7)

    Output:

    odd number
    even number
    odd number

    Example 3:

    Python3

    def multiply_num(a):

        b = 40

        r = a*b

        return r

    z = multiply_num

    print(z(6))

    print(z(10))

    print(z(100))

    Output:

    240
    400
    4000

    Not unless you are going to use "exec()" and people advise against that.

    The second way is a good way.

    class Test:
        def Testing(self):
            # Run function
    
    x = Test()
    x.Testing()

    Jump to Post

    Simply store the reference to the function in the variable. Here is example:

    def one():
        print("hello from function one")
    
    def two():
        print("hello from function two")
    
    def three():
        print("hello from function three")
    
    # stores the ref of function in variable
    f1 = one
    f2 = two
    f3 = …

    Jump to Post

    All 8 Replies

    Python store function in variable with arguments

    redyugi 5 Junior Poster in Training

    12 Years Ago

    Not unless you are going to use "exec()" and people advise against that.

    The second way is a good way.

    class Test:
        def Testing(self):
            # Run function
    
    x = Test()
    x.Testing()

    Python store function in variable with arguments

    bumsfeld 413 Nearly a Posting Virtuoso

    12 Years Ago

    Simply store the reference to the function in the variable. Here is example:

    def one():
        print("hello from function one")
    
    def two():
        print("hello from function two")
    
    def three():
        print("hello from function three")
    
    # stores the ref of function in variable
    f1 = one
    f2 = two
    f3 = three
    func_list = [f1, f2, f3]
    
    for f in func_list:
        # show the function reference
        print(f)
        # call the function
        f()
    
    """my display -->
    
    hello from function one
    
    hello from function two
    
    hello from function three
    """

    Python store function in variable with arguments

    redyugi 5 Junior Poster in Training

    12 Years Ago

    Simply store the reference to the function in the variable. Here is example:

    def one():
        print("hello from function one")
    
    def two():
        print("hello from function two")
    
    def three():
        print("hello from function three")
    
    # stores the ref of function in variable
    f1 = one
    f2 = two
    f3 = three
    func_list = [f1, f2, f3]
    
    for f in func_list:
        # show the function reference
        print(f)
        # call the function
        f()
    
    """my display -->
    
    hello from function one
    
    hello from function two
    
    hello from function three
    """

    I never knew I could do that. I knew you could do it with a class instance but...thanks

    Python store function in variable with arguments

    12 Years Ago

    Awesome. That solves a tonne of problems. Thanks. =)

    Python store function in variable with arguments

    4 Years Ago

    I need help on my Python project. I am creating a guess the number game and I need to include a menu, collect statistics, and plot statistics results. I have already created the game, but I don't know how to include a menu, collect statistics, or plot the results. Please help!!

    Python store function in variable with arguments

    3 Years Ago

    Hi,
    I too have same functinality like you guys posted here...
    it iis working fine when I pass arguments to defined functions.

    going wrong if the function is specified with "self"

    Ex:

    class Anyclassname:
        def __init__ (self, a):
            self.a = a
        def one(self, dicti):
            print("hello from function one")
            print(self.a, dicti)
    
     ## Assume that instance is created  function is called refering eith instance
    
     for f in func_list:
         # show the function reference
         print(f)
         # call the function
         dicti = {'1': 'one'}
         f(dicti)
    
    #throwing error as "Print the exception one() missing 1 required positional argument: 'dicti'"

    Please help me with this...

    Python store function in variable with arguments

    3 Years Ago

    Hi @Akshay_15,

    Why not post your question as a new topic instead of commenting on an old post here ?

    Edited 3 Years Ago by John_165

    Python store function in variable with arguments

    1 Year Ago

    class Callback:
        def __init__(self, fun, *args, **kwargs):
            self.fun = fun
            self.args = args
            self.kwargs = kwargs
    
        def __call__(self):
            self.fun(*self.args, **self.kwargs)
    
    def say(message):
        print(message)
    
    
    if __name__ == "__main__":
        callback = Callback(say, message="Hello")
        callback()

    This would be more general solution.

    Edited 1 Year Ago by tomas_petricek

    Reply to this topic

    Be a part of the DaniWeb community

    We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.

    Can you store a function in a variable Python?

    In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want.

    How do you store functions in a variable?

    Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.

    Can I put a function inside a list Python?

    Answer: You can use any expression inside the list comprehension, including functions and methods. An expression can be an integer 42 , a numerical computation 2+2 (=4) , or even a function call np. sum(x) on any iterable x . Any function without return value, returns None per default.

    How do you call a function variable in Python?

    To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.