1

I have a question regarding return convention in Python. I have a class that has some data attributes and I have several functions that perform some analysis on the data and then store the results as results attributes (please see the simplified implementation below). Since, the analysis functions mainly update the results attribute, my question is what is the best practice in terms of return statements. Should I avoid updating class attributes inside the function (as in process1), and just return the data and use that to update the results attribute (as in process2)?

Thanks, Kamran

class Analysis(object):

    def __init__(self, data):
        self.data = data
        self.results = None

    def process1(self):
        self.results = [i**2 for i in self.data]

    def process2(self):
        return [i**2 for i in self.data]



a = Analysis([1, 2, 3])
a.process1()
a.results = a.process2()
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
kamraider
  • 11
  • 1
  • 3
    Does anything else in the class use the results? *Why* do you store the results like that? Could whatever needs the results trigger the process to calculate them (after which the results are cached)? – Martijn Pieters Nov 28 '17 at 17:53
  • Please try to make your title reflect your actual question, not just the broad topic of that question. I've done my own edit towards that end -- hopefully it's an accurate interpretation. – Charles Duffy Nov 28 '17 at 17:55
  • 1
    Generally speaking, Python types return `None` when a method mutates the state in-place. E.g. `list.sort()` and `list.append()` and `dict.update()` all return `None`, because they all mutate the object state. – Martijn Pieters Nov 28 '17 at 17:56
  • I personally feel that a method updating object state should return the object itself so as to allow chaining of such "in-place" operations. – Paul Panzer Nov 28 '17 at 18:06
  • @MartijnPieters Yes, other functions in the class also use the results attribute that's why I need to cache them. – kamraider Nov 28 '17 at 19:34
  • @CharlesDuffy Thanks so much for improving the title of the question. This is my first post ever on stack and I appreciate the useful tip going forward. – kamraider Nov 28 '17 at 19:36

1 Answers1

0

It all depends on the use case.

First of all, You are not changing the class attributes there. You are changing the instance attributes.

Python: Difference between class and instance attributes

Secondly, If you are planning to share the results of your process among the various instances of the class,Then you can use class variables.

Third, If you are asking about instance variables, Then it depends on design choice.

Besides that, This is unnecessary I guess:-

a.results = a.process2()

You simply made allocation to be part of object itself. You can use a.process2 function for displaying results if you need that functionality.

gautamaggarwal
  • 341
  • 2
  • 11