Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: pass method as argument in function

I've seen a lot of posts but none really addressing my question. With Python, I am trying to pass a method as an argument in a function which requires two arguments:

# this is a method within myObject
def getAccount(self):
    account = (self.__username, self.__password)
    return account
# this is a function from a self-made, imported myModule
def logIn(username,password):
    # log into account
    return someData
# run the function from within the myObject instance
myData = myModule.logIn(myObject.getAccount())

But then Python's not happy: it wants two arguments for the logIn() function. Fair enough. If thought the problem was that the getAccount() method returned a tuple, which is one object. I tried then:

def getAccount(self):
    return self.__username, self.__password

But that either did not make a difference.

How then can i pass the data from getAccount() to logIn()? Surely if i don't understand that, i am missing something fundamental in the logic of programming :)

Thanks for helping. Benjamin

like image 748
neydroydrec Avatar asked May 04 '11 09:05

neydroydrec


2 Answers

You want to use python argument unpacking:

myData = myModule.logIn( * myObject.getAccount() )

The * before an argument to a function signals that the following tuple should be split into its constituents and passed as positional arguments to the function.

Of course, you could do this by hand, or write a wrapper that takes a tuple as suggested by others, but unpacking is more efficient and pythonic for this case.

like image 176
Andrew Jaffe Avatar answered Oct 01 '22 00:10

Andrew Jaffe


This

myData = myModule.logIn( * myObject.getAccount() )
like image 20
S.Lott Avatar answered Sep 30 '22 22:09

S.Lott