Forum Archive

Use a predefined function with parameters

macnfly

I have this code but it seems impossible for me to save the function to a variable with parameters and call it later on.

from scene import *

class MyScene (Scene):
    def setup(self):
        self.a = test(200,200)

    def draw(self):
        background(0, 0, 0)
        test(100,100)
        #how do I call self.a with its parameters

run(MyScene())

def test(x,y):
    rect(x,y,20,20)

Test(100,100) works fine !
Re Peter

ccc

There is a better answer but...

def test(x = 200, y = 200):
    return rect(x, y, 20, 20)

Do you want 'return' on that last line?

Sebastian

You can use partial from the functools library. Like this:


from scene import *
from functools import partial

class MyScene (Scene):
def setup(self):
self.a = partial(test, 200, 200)

def draw(self):
    background(0, 0, 0)
    #test(100,100)
    self.a()

run(MyScene())

def test(x,y):
rect(x,y,20,20)

macnfly

Ohhh thanks, just what I was after :-)
Python has all these smart bits, but sometimes hard to find if you do not know what to search for. Like this one, the name does not tell exactly.

Re Peter

Sebastian

I forgot to mention that you can also use python's lambda to accomplish this.

from scene import *

class MyScene (Scene):
def setup(self):
self.a = lambda: test(200, 200)

def draw(self):
    background(0, 0, 0)
    #test(100,100)
    self.a()

run(MyScene())

def test(x,y):
rect(x,y,20,20)