Trying to return 'datetime.date' instead using yield

489 views Asked by At

I have this function. It return range dates from today, but I need to use this result twice. If I replace 'yield' with 'return' I got TypeError: 'datetime.date' object is not iterable

def date_range():
    start_date = datetime.date.today()
    end_date = start_date + datetime.timedelta(days=11)
    for n in range(int((end_date - start_date).days)):
        yield start_date + timedelta(n)
1

There are 1 answers

5
Martijn Pieters On BEST ANSWER

Rather than 'fix' the function, convert the result of the function to a list:

dates = list(date_range())

The list() function then iterates over all the results produced by the generator function and builds a list object from them. You can then iterate over that list object as many times as you like.

The alternative would be to convert the function to return a list rather than generate the date objects one by one:

def date_range():
    start_date = datetime.date.today()
    return [start_date + timedelta(n) for n in range(11)]

This uses a list comprehension to produce the whole list from the same loop. Note that the end_date calculation was entirely redundant since you then go back to a timedelta and even to an integer number of days!

Similarly, your generator function version can be simplified to:

def date_range():
    start_date = datetime.date.today()
    for n in range(11):
        yield start_date + timedelta(n)