I was unable to find a reasonable way to create a variable which calls a function requiring parameters.
Here is a simplified version of my code. I would like print_hello
to print hello
when it is called, and not when it is defined.
print_hello = print('hello')
When I define print_hello
, it calls print('hello')
. When I call print_hello
, it gives me an error. How do I fix this?
Just define print_hello
as a lambda function
>>> print_hello = lambda: print('hello')
>>> print_hello()
hello
To delay execution, you'll have to wrap the call to print
in another function. A lambda is less code than defining another function.
Note: that pep08 recommends using a def function rather than a lambda when assigning to a variable. See here. So @Sheldores answer is probably the way to go.