Nelson Guaman Leiva Nelson Guaman Leiva - 7 months ago 10
Python Question

what is the correct way to return a value inside of a method? in python

This function makes a range of dates (this function is related to a class):

def _makeRangeDates(self, desde, ultima_carga):
dates = []
for fechaRequest in rrule(DAILY, dtstart=desde, until=ultima_carga):
dates.append(fechaRequest)
return self.dates


What is the best way to return the list of dates inside of this function?

is mandatory to return self.dates ?

Regards.
Nelson.

Answer

I'm assuming that you've got this function in some sort of class foo like so:

class foo(object):
    def __init__(self):
        self.dates = []

    def _makeRangeDates(self,desde,ultima_carga):
        dates = []
        for fechaRequest in rrule(DAILY, dtstart=desde, until=ultima_carga):
            dates.append(fechaRequest)
        return self.dates

In this case returning dates and self.dates are two totally different things. Since dates is created within the _makeRangeDates function, it will be garbage collected soon after the function is called. If you're looking to just return dates and not save it in some state then that's perfect fine.

If you're hoping to save the state of dates then do the following:

class foo(object):
    def __init__(self):
        self.dates = []

    def _makeRangeDates(self,desde,ultima_carga):

        for fechaRequest in rrule(DAILY, dtstart=desde, until=ultima_carga):
            self.dates.append(fechaRequest)
        return self.dates