Home > Mobile >  Alternative to return multiple values from function in python in a structured way?
Alternative to return multiple values from function in python in a structured way?

Time:06-18

I'm working on mortgage calculations and many functions calculate multiple different values that I need to return.

For example:

def calculate_something(incomes, debts):
    ...
    return {'value':150000, 'extra':{'dsti_gross':450, 'dsti_supergross':480}}

has many intermediate calculations that are useful in other calculations. These functions are not divisible into smaller functions as it would make the code slower.

I don't want to return tuples as the code might change in the future and I'd need to check all the function calls.

Dictionary is now a way to go but dictionary value calls aren't statically analyzed (most IDEs) so you always need to check the function if you access the correct keys.

Is there another way to work with such returns? Considering classes/objects but every function returns different keys.

CodePudding user response:

To expand on the suggestion to use classes and subclasses, you can take advantage of python dataclasses, which are pretty much designed for such a problem.

  • Related