Python, About UnboundLocalError occurring in the if or for statement

Question:

  1. An error occurred during the process of utilizing the notion API.
  2. I want to categorize the titles separately and make them look good, but my code can’t find the variable ‘title’.

ERR: UnboundLocalError: local variable ‘title’ referenced before assignment

import requests, json


def read_database(database_id, token):
    """
    A function that receives and returns information from the database id
    """
    headers = {
        "Authorization": "Bearer " + token,
        "Notion-Version": "2022-06-28"
    }
    read_url = f"https://api.notion.com/v1/databases/{database_id}/query"

    res = requests.request("POST", read_url, headers=headers)
    data = res.json()

    if res.status_code == 200:
        key_data = list(data["results"][0]["properties"].keys())
        print("Data lookup successful")

        for i in data["results"][0]["properties"]:
            if "title" in i:
                title = i
                print(title)

        print(f"The total number of columns is  {len(key_data)} and the name of each item is")
        print(f"{', '.join(key_data)}.")
        print(f"The title type is {title} here.")

Below is the full error code.

Traceback (most recent call last):
  File "/Users/notion_API/main.py", line 10, in <module>
    read_database(database_id, token)
  File "/Users/notion_API/notion_function.py", line 36, in read_database
    print(f"The title type is {title} here.")
UnboundLocalError: local variable 'title' referenced before assignment

It’s a problem I’ve had since I started Python.
I’m taking this opportunity to ask you a proper questionPlease give me some advice

Asked By: coovi

||

Answers:

Directly after the line
if 'title' in i the variable line is initialized.

In the case where this if-statement results in False, it doesn’t get executed and title doesn’t get a value.

This is what happened, ‘title’ wasn’t in i and as a result of this, the variable ‘title’ was never initialized.

To fix this, you need to initialize ‘title’ in some way, even if there’s no data provided for it.
An alternative would be to omit the print-call if there’s no data provided for ‘title’.

Answered By: Hyalunar

actually UnboundLocalError error is self-exploratory.
if you trace your code closely enough :

if "title" in i:
    title = i
    print(title)

if this condition is not satisfied, your variable title will not get declared.
while your print statement : print(f"The title type is {title} here.") is outside of the condition.

Answered By: Asav Patel

Thank you for your kind reply.
I think it didn’t work out because I was thinking with a hazy head at dawn.
I woke up in the morning and looked at your advice and code again to find the problem.

# I didn’t realize that if I put a dictionary in the for syntax, only the key value would come out.

# As a result, the problem occurred because you tried to find the key "title" in the simple string format.

# I found "title" by putting the key value in the for statement.

Below is the modified code.

def read_database(database_id, token):
    """
    A function that receives and returns information from the database id
    """
    headers = {
        "Authorization": "Bearer " + token,
        "Notion-Version": "2022-06-28"
    }
    read_url = f"https://api.notion.com/v1/databases/{database_id}/query"

    res = requests.request("POST", read_url, headers=headers)
    data = res.json()

    if res.status_code == 200:
        key_data = list(data["results"][0]["properties"].keys())
        print("Data lookup successful")

        for i in key_data:
            if "title" in data["results"][0]["properties"][i]:
                print(i)
                title = i
        # for i in data["results"][0]["properties"]:
        #     print(i)
        #     print(type(i))
        #     if "title" in i:
        #         title = i
        #         print(type(i))


        print(f"The total number of columns is  {len(key_data)} and the name of each item is")
        print(f"{', '.join(key_data)}.")
        print(f"The title type is {title} here.")

Once again, thank you to everyone who kindly answered the stupid question.

Especially, "Tim Roberts". Thank you

Answered By: coovi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.