'How can I store a function with parameters as a variable without calling it immediately?
I am creating a translator for my Raspberry Pi that will get an input, then output the Morse code with an LED.
I have a function that will accurately output the Morse code for the letter of my choosing. I am trying to assign the function with parameters to a variable for quicker access like this:
a = letter(dot, dash)
but when I try and store it like that it runs the function with those parameters, I also can't call it with something like a().
Solution 1:[1]
Yes, you can use partial for this:
from functools import partial
a = partial(letter, dot, dash)
Partial constructs a new function. If that function is called, it will call letter with dot and dash. In case you call a with parameters, those parameters are added at the end (the unnamed parameters), and the named parameters are updated.
Solution 2:[2]
You can set a variable to a function and then use the variable as the function's name. Here is an example:
def cube(number):
return number ** 3
make_cube = cube # Take out those parentheses
Now, the variable make_cube can be used as a function, like so:
print(make_cube(2))
# 8
Both cube and make_cube point to the same memory address, which you can confirm with id(make_cube) == id(cube).
In your case, it can be:
a = letter
a(dot, dash)
Solution 3:[3]
You can also write the function expression as string and later on call using eval.
a = "letter(dot, dash)"
eval(a)
(Does not require importing of module)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willem Van Onsem |
| Solution 2 | |
| Solution 3 |
