Reputation: 658
I created function which parses JSON file for subtask issue. Depending of number of tickets, this function sometimes return 1, sometimes more lines and sometimes returns nothing.
def subtask():
for issue in data['issues']:
for subtask in issue['fields']['subtasks']:
if subtask['fields']['summary'] != 'Workspace created':
x = subtask['fields']['summary']
return x
Next I pass output of this variable to if
block: It simply checks if function output contains words other than "Workspace created".
x=subtask()
for issue in data['issues']:
if len(issue['fields']['subtasks']) == 0 or x != "Workspace created":
print issue['key']
print issue['fields']['description']
It works as expected when subtasks()
function returns any value, but fails if there is no output from function:
UnboundLocalError: local variable 'x' referenced before assignment
How to specify default value for function if no output?
for example x=""
I tried:
def subtask(x=None):
for issue in data['issues']:
for subtask in issue['fields']['subtasks']:
if subtask['fields']['summary'] != 'Workspace created':
x = subtask['fields']['summary']
if x is None:
x = "test"
return x
But it returns "test" for tickets with and without summary fields.
Upvotes: 0
Views: 57
Reputation: 658
i simplified code (removed function)
data = response.json()
for issue in data['issues']:
for subtask in issue['fields']['subtasks']:
s = subtask['fields']['summary']
if len(issue['fields']['subtasks']) == 0 or subtask['fields']['summary'] != "Workspace created":
print issue['fields']['description']
print issue['key']
Upvotes: 0
Reputation: 1343
The issue is that, if the condition if subtask['fields']['summary'] != 'Workspace created':
never becomes true, then x
is not initialized and thus the error of local variable 'x' referenced before assignment
The problem with your second code is similar, if "first if - condition" is not true there is no x
for "second if - condition".
To fix this just set x=None
before going into loop.
def subtask():
x = None # set default value of x here
for issue in data['issues']:
for subtask in issue['fields']['subtasks']:
if subtask['fields']['summary'] != 'Workspace created':
x = subtask['fields']['summary']
return x
Upvotes: 1