MySQLdb error local variable referenced before assignment (different than usual)
<p>I am attempting to add some data to MySQL database via a loop that iterates through the API that returns a JSON file. I am using Python and MySQLdb module. </p>

<p>For some reason I am getting the infamous UnboundLocalError. I looked at the other scenarios when this problem occurred and that have already been answered on StackOverflow but nothing resonated with me and I couldn't apply it directly to this problem. </p>

<p>Here's my code:</p>

<pre><code>def request(API_KEY, URL, ch_no):
    url = URL + ch_no + '/request'
    request = requests.get(url, auth=(API_KEY, ''))
    data_dict = request.json()
    data_dict_json_dumps = json.dumps(data_dict)
    data = json.loads(data_dict_json_dumps) 

    try:
        for item in data['items']:
            return (item['tag'], item['created_on'], item['delivered_on'], item['satisfied_on'], item['status'], item['particulars']['description'], item['persons_entitled'][0]['name'])   
    except KeyError:
        pass

    try:
        description = item['particulars']['description']
    except KeyError:
        description = None
    try:
        persons_entitled = item['persons_entitled'][0]['name']
    except KeyError:
        persons_entitled = None 

    try:
        cursor.execute("""INSERT INTO companies_and_charges_tmp (tags, company_id, created, delivered, satisfied, status, description, persons_entitled) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""", (item.get('tag'), ch_no, item.get('created_on'), item.get('delivered_on'), item.get('satisfied_on'), item.get('status'), description, persons_entitled))
    db.commit()

    finally: 
        time.sleep(0.5)

    del data

for ch_no in ch_nos:
    charges_request(API_KEY, URL, ch_no)
</code></pre>

<p>And here's the full error:</p>

<pre><code>Traceback (most recent call last):
  File "test2.py", line 58, in &lt;module&gt;
    charges_request(API_KEY, URL, ch_no)
  File "test2.py", line 49, in charges_request
    cursor.execute("""INSERT INTO companies_and_charges_tmp (etags, company_id, created, delivered, satisfied, status, description, persons_entitled) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""", (item.get('etag'), ch_no, item.get('created_on'), item.get('delivered_on'), item.get('satisfied_on'), item.get('status'), description, persons_entitled))
UnboundLocalError: local variable 'item' referenced before assignment
</code></pre>