Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a value into a python function without calling?

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?

like image 958
Bilbo Baggins Avatar asked Aug 23 '26 16:08

Bilbo Baggins


2 Answers

If you just want a function that does precisely what you describe, Sheldore's answer is the simplest way to go (and more Pythonic than using a named lambda).

An alternative approach is to make a partial application of the function with functools.partial, which allows you to pass additional arguments at call time:

from functools import partial

print_hello = partial(print, "hello")

print_hello()  # Prints "hello" to stdout

print_hello(file=sys.stderr)  # Prints "hello" to stderr

print_hello("world")  # Prints "hello world" to stdout
like image 78
ShadowRanger Avatar answered Aug 26 '26 05:08

ShadowRanger


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.

like image 42
Paul Rooney Avatar answered Aug 26 '26 06:08

Paul Rooney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!