Unpack and assign a single return value from a multi-return function in one line (Python)

Viewed 48

I'm trying to do the following, but it's not working:

agreements = getEligibleAndActiveAgreements(username).eligibleAgreements

for a function which returns 2 results. I don't want to assign a general variable first, like result = .., and then check result.eligibleAgreements, I want to quickly assign on the same line to a specific variable from just one return.

def getEligibleAndActiveAgreements(username):
    ...
    return eligibleAgreements, activeAgreements

Error for getEligibleAndActiveAgreements(username).eligibleAgreements

AttributeError: 'tuple' object has no attribute 'eligibleAgreements' 

Error for getEligibleAndActiveAgreements(username)['eligibleAgreements']

TypeError: tuple indices must be integers or slices, not str
2 Answers

Try either of these:

agreements, _ = getEligibleAndActiveAgreements(username)
# OR
agreements = getEligibleAndActiveAgreements(username)[0]

The function returns a tuple containing both values. In order to access the values independently you need to use index values (starting at 0) or just unpack into agreements and discard the other one.

The references of returned variables are known only locally inside function, when you call the function it doesn't know the references from the return x,y line, it's just a tuple outside function.

So you can do:

eligibleA, activeA = getEligibleAndActiveAgreements(username)

Or alternatively just return dict:

def getEligibleAndActiveAgreements(username):
    ...
    return {"eligibleAgreements": eligibleAgreements, "activeAgreements": activeAgreements}
...
agreements = getEligibleAndActiveAgreements(username)

eligibleAgreements = agreements["eligibleAgreements"]
Related