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
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.
This
myData = myModule.logIn( * myObject.getAccount() )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With