Home > Enterprise >  local variable 'issue' referenced before assignment
local variable 'issue' referenced before assignment

Time:11-11

My main function


    for record in event["Records"]:
        payload = json.loads(record["body"])
        if payload["action"] != "Create":
            continue
        issue_id = payload["documentId"]["id"]
        if issue_id is None:
            issue_id = payload["documentId"]["id"]
        issue = client.get_issue(issue_id)

    data_id, main_id = parse_issue(client, issue)


Error: local variable 'issue' referenced before assignment data_id, main_id = parse_issue(client, issue)

I need to be able to pass issue as I am also using it to one of my function above. Should I place the issue = client.get_issue(issue_id) outside for loop?

def parse_issue(client, issue):

    data_id = issue.data["id"]
    main_id = issue.main_id

## More Code
    return data_id, main_id

CodePudding user response:

It should be ok just to define your variable at the higher scope so that all the functions can see it. Everything in python is based on how much it's indented. So if you put down a variable at the same indent level as the for loop and the call to the function, it will store the value outside of the for loop and be accessible to both:

issue = 0
for record in event["Records"]:
    payload = json.loads(record["body"])
    if payload["action"] != "Create":
        continue
    issue_id = payload["documentId"]["id"]
    if issue_id is None:
        issue_id = payload["documentId"]["id"]
    issue = sim_client.get_issue(issue_id)

data_id, main_id = parse_issue(client, issue)

CodePudding user response:

The reason is because issue never gets assigned a value. If there is nothing in event["Records"], or continue always happens, then the issue = client.get_issue(issue_id) gets skipped.

Example:

def func():
    for i in range(0):
        x = 1 # never happens
    print(x)
func()
UnboundLocalError: local variable 'x' referenced before assignment
  • Related