Is it an unusual design pattern to assign output of function to many variables? Imagine each variable below representing complex data, such as nested dictionaries.
def step_1():
a = ...
...
i = ...
return a, b, c, d, e, f, g, h, i
def step_2(a, b, c, d, e, f):
...
return j
def step_3(g, h, i, j):
...
return k
a, b, c, d, e, f, g, h, i = step_1()
j = step_2(a, b, c, d, e, f)
k = step_3(g, h, i, j)
# do something with k
Somehow it feels odd doing things like
a, b, c, d, e, f, g, h, i = step_1()
or
return a, b, c, d, e, f, g, h, i
or
j = step_2(a, b, c, d, e, f)
.
CodePudding user response:
Generally in such cases a seperate dictionary is maintained with all the outputs being stored it has many issue. you can save it as json easily or even you can pass required fields from it manually but this makes the redability of the code much more.
For example here final_output = {"a":a,'b':b,'c':c}
and returning this final_output
instead. This actually I use it in for business purposes.
CodePudding user response:
If you're returning a,b,c,...,i
, that's a bit excessive, though in general this isn't (necessarily) a poor design choice. In reality, this is the product of two Python features:
- From the
return
statement, Python is interpreting/ treating the return type as a tuple that, syntactically, has been expanded, rather than treating it as the union of however many variables individually. That is, you could equivalently define a tupletuple = (a,...,i)
and return that. - Then again when you assign the
a, ..., i = step1()
, you're again expanding this tuple.
What you might consider is treating it as a tuple, ie, a single object, rather than 9 individual items, since it doesn't seem that you need all of them at once. This might be better for code style, etc.
Since you make the distinction that these a,...,i
are "complex data" items, though you have given little about your particular case, it's probably best to split up this functionality to make its scope as clear, tight, and therefore manageable as possible. If I was working with you, I'd probably implore you to do so before I'd write any unit tests for it.