Try-except-finally block won't assign a variable within the except block: if "access_token" in result.keys(): print("Successful token acquisition from:", result["token_source"]) # Since MSAL 1.25 # Calling a web API using the access token r = requests.get( queryURL, headers={'Authorization': 'Bearer ' + result['access_token'], 'Prefer':'odata.include-annotations="OData.Community.Display.V1.FormattedValue"'}, ) t = r.text api_result = r.json() try: query = api_result['value'] except KeyError: (THIS LINE) query = api_result if 'error' in api_result: err_code, err_msg = api_result['error'].items() raise DataverseError(err_code, err_msg) raise NoValuesBlockError(api_result.keys()) finally: return query else: raise TokenAcquisitionError(value=result) api_result.keys() = dict_keys(['@odata.context', '@odata.type', 'ParentOptionSetName', 'IsCustomOptionSet', 'IsGlobal', 'IsManaged', 'Name', 'ExternalTypeName', 'OptionSetType', 'IntroducedVersion', 'MetadataId', 'HasChanged', 'Options', 'Description', 'DisplayName', 'IsCustomizable']) but query isn't assigned to api_result in the highlighted line. There is a case where there will be no values block, nor an error block, that should be caught and still returned. Continue reading...