Rajon Ali Rajon Ali - 7 months ago 9
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:

size(1000,500)
background(255,255,255)
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]
y=0

def palette():
global y
global mcolors
for i in mcolors:
i
rect(0,y,20,20)
y+=22
palette() `

Answer

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.:

i()

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:

fill(*i)

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

Comments