Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set a function as a default argument?

I have recently found out that a function can be used like this:

def func():
    print("Hello World!")


def run_func(name_of_func):
    name_of_func()


run_func(func)  # Prints "Hello World!"

A function name is used as an argument. So my question is if a default argument can be used in this situation. More specifically, if run_func() is called without an argument, can there be a default argument so my program outputs nothing and ends without raising an error?

There are similar functions like this for scheduling a function and looping it. However, when the function is called, an argument must be put in or it will result in an error (basically there is no default argument).

like image 760
Scene Avatar asked Feb 11 '26 21:02

Scene


1 Answers

Yes.

def func():
    print("Hello World!")


def run_func(name_of_func=func):
    name_of_func()


run_func()  # Prints "Hello World!"
like image 106
Javier Avatar answered Feb 15 '26 16:02

Javier