Search code examples
pythonlistfunctionreturngoogle-calendar-api

Returning a list from function


I know, the question is dumb and easly googleable on internet. I did it, and that did not help me. I'm working with the Google Calendar API for Python (3.7.1)

from dateutil.parser import parse as dtparse
from datetime import datetime as dt
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'

start = '2018-12-26T10:00:00+01:00'   # Let's say your start value returns this as 'str'
tmfmt = '%d %B, %H:%M %p'


class Calendar():

    def getEvents(self):
        """Shows basic usage of the Google Calendar API.
        Prints the start and name of the next 10 events on the user's calendar.
        """
        # The file token.json stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        store = file.Storage('token.json')
        creds = store.get()
        if not creds or creds.invalid:
            flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
            creds = tools.run_flow(flow, store)
        service = build('calendar', 'v3', http=creds.authorize(Http()))

        # Call the Calendar API
        now = dt.utcnow().isoformat() + 'Z'  # 'Z' indicates UTC time
        events_result = service.events().list(calendarId='primary', timeMin=now,
                                              maxResults=10, singleEvents=True,
                                              orderBy='startTime').execute()
        events = events_result.get('items', [])
        if not events:
            print('No upcoming events found.')
        for event in events:
            start = event['start'].get('dateTime', event['start'].get('date'))
            stime = dt.strftime(dtparse(start), format=tmfmt)
            items = str(stime + event['summary'])
            print(items)
            return items

"""
 Tried aswell   str1 = ''.join(str(e) for e in items)
                return str1
"""


    def Events(self):
        print(self.getEvents())


x = Calendar()
x.Events()

I modified it in order to return the events with a human readable date format. Anyway, when i print(stime + event['summary']) in getEvents(), I get a normal output.. When i try to print it in another function (at last it shall be displayed in a tkinter label), It either doesn't work, or it prints the first item, or the last one...

How is this achieved?


Solution

  • Returning a list is achieved by literally returning a list object, not calling return multiple times.

    Indeed, your function will exit the first time it encounters a return statement. For example:

    >>> def func():
    ...     return 1
    ...     return 2
    ...     return 3
    ... 
    >>> func()
    1
    

    We don't get a list of [1, 2, 3] - we exit with the value returned by the first return we encounter.

    Specifically, you have a return inside a loop. This will cause the function to exit on the first iteration through this loop.

    Your loop over events probably wants to look like this instead:

    ret = []
    for event in events:
        # ... snip...
        ret.append(items)
    return ret
    

    You probably want to consider renaming some variables too - items, for example, only refers to a single item.