Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more pythonic way of storing parameters so they can be used in a function call?

Tags:

python

I'm currently writing a small script using pygame, but I don't believe this question to be related strictly to pygame.

I have a class that holds a dictionary of function parameters contained in tuples:

self.stim = {1:(firstParam, secondparam, thirdparam),
            2:(firstParam2, secondparam2, thirdparam2),
            3:(firstParam3, secondParam3, thirdParam3)}

In the same class, I have a function that issues a call to another function using these parameters:

def action(self, stimType):
    pygame.draw.rect(self.stim[stimType][0], self.stim[stimType][1], self.stim[stimType][2])

It works, but it's a bit ugly to read. I was wondering if there was a more elegant way of storing these parameters such that a function can be called using them?

Thanks!

like image 294
Louis Thibault Avatar asked Jan 28 '12 19:01

Louis Thibault


1 Answers

Sure, it is called argument list unpacking (thanks Björn Pollex for the link):

def action(self, stimType):
    pygame.draw.rect(*self.stim[stimType])

And if you are not using a dict for any particular reason, then a tuple for the collection of different arguments is better suited and more peformant:

self.stim = (
    (firstParam, secondparam, thirdparam),
    (firstParam2, secondparam2, thirdparam2),
    (firstParam3, secondParam3, thirdParam3)
)

Just remember that the indexes now start at 0: self.stim[stimType] becomes self.stim[stimType-1]

like image 142
GaretJax Avatar answered Nov 10 '22 08:11

GaretJax