0

Reference: Python 3: UnboundLocalError: local variable referenced before assignment

I tried passing parsed_upd as argument and also tried defining as global, I'm still getting the same error

parsed = dict()

def func1(str1):
    global parsed
    header=str1.split('[',1)[0]
    body=str1.split('[',1)[1]
    header_parts=header.split(' ')
    parsed['timeStamp']=header_parts[1]
    parsed['eventDate']=header_parts[1].split('T')[0]
    parsed['eventType']=header_parts[5].upper()
    body_str=body[:]
    esc=0
    start=0
    end=0
    body_parts=list()
    while True:
        try:
          esc = body_str.index('\\]', start)
        except:
          esc = 0
        try:
           start = start+1 if body_str[start:-1][0]=='[' else start
           end = body_str.index(']', start)
        except:
           end = 0
           if (esc > 0 and esc != end):
             continue
        if (end > 0):
           body_parts.append(body_str[start:end])
           start = end + 1
        if (end == 0):
            break

    if (not check(body_parts, 'guId=')):
         parsed['eventType'] = 'ERROR_' + header_parts[5].upper()
    list_attr = list()
    for item in body_parts:
        list_attributes = [attrib_dict.strip('"') for attrib in item.split('" ') for attrib_dict in attrib.split('="', 1)]
        m = re.search(r'([a-zA-Z]*)(@)([0-9]*)\s+(.+)', list_attributes[0])
        if m:
            if (not m.group(1).lower().startswith('requestcontext')):
                parsed['eventName'] = m.group(1)
            list_attributes[0] = m.group(4)
        else:
            print('Empty list_attributes : {}'.format(list_attributes[0]))
            list_attributes.pop(0)
        list_attr += list_attributes
        parsed_upd = merge(parsed, dict(zip(*[iter(list_attr)] * 2)))
    print(parsed_upd)
    return parsed_upd

Getting the error in the return statement. Using Python version 2.7.5

  • 1
    Maybe `body_parts` stays as an empty list. So for loop does not run a single time and therefore no value is assigned to `parsed_usd` – Shadowcoder Feb 27 '21 at 08:18

1 Answers1

0

It was an indentation issue

parsed_upd = merge(parsed, dict(zip(*[iter(list_attr)] * 2)))

The above line should be outside the loop.