I have the following functions in Python3.7
def output_report():
sheet_dict = {1: 'All', 2: 'Wind', 3: 'Soalr'}
sheet_name = sheet_dict[sheet_num]
file_name = f'{file_name}_{sheet_name}_row_{row_num}.csv' if row_num else
f'{file_name}_{sheet_name}.csv'
return file_name
def test_file(x):
file_name = output_report(sheet_num)
return f'{x}_{file_name}'
def good_func():
sheet_num = 2
row_num = 2
a = test_file('new file')
return a
when I call: good_func()
It raises an error that:
NameError: name 'sheet_num' is not defined
But if I define sheet_name and row_num in the global scope like,
sheet_num = 2
row_num = 2
def good_func():
a = test_file('new file')
return a
the code works.
My question: My understanding was that in nested functions, the inner functions starts looking for the variables from itself and then goes to outer functions and finally to the global scope. Then, I expected the first function also runs, but that's not the case. What is that? I read other scope related questions but didn't find my answer.