Rajon Ali Rajon Ali - 5 months ago 6x
Python Question

Declare python variable that stores a function, but not run it

I am trying to declare a python variable that stores a function with the desired parameters, but when I run it, it runs the last declared variable. I am trying to store it in a variable and when I write the variable name, it runs the function with parameters associated. It is meant to run in a program called Processing:

cred = fill(255,0,0)
corange = fill(255,127,0)
cyellow = fill(255,255,0)
cgreen = fill(0,255,0)
cblue = fill(0,0,255)
cpurple = fill(143,0,255)

mcolors = [cred,corange,cyellow, cgreen, cblue, cpurple]

def palette():
global y
global mcolors
for i in mcolors:
palette() `


One way would be to wrap the calls in lambda functions:

cred = lambda: fill(255, 0, 0)

To call it you would still need the (), i.e.:


However I think in this case it might be better to just store the color values rather than the actual function references, i.e.:

cred = (255, 0, 0)

This creates a tuple of the values (kind of like an immutable list). It's different from the function call parenthesis. Then later you could pass these to a function in your loop:


The star operator will make it use the values from the tuple as separate arguments rather than one argument.