Python pass function as argument | Example code

Just use the name of the function as a argument for another function. Methods and functions are objects in Python, just like anything else, and we can pass them around the way do variables.

Functions (and methods) are first class objects in Python. So you can pass function as an argument into another one in python.

function_1(funtion_2)

Example passing function as an argument in Python

Simple example code.

Passing bar() funciton as a argument into a foo() funciton.

def foo(f):
    print("Running parameter f().")
    f()


def bar():
    print("In bar().")


foo(bar)

Output:

Python pass function as argument

Another example

def up_text(text):
    return text.upper()


def low_text(text):
    return text.lower()


def greet(func):
    # storing the function in a variable
    greeting = func("Hello, Function")
    print(greeting)


greet(low_text)
greet(up_text)

Output:

HELLO, FUNCTION
hello, function

Do comment if you have any doubts and suggestions on this Python function tutorila.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.