Hello pyRevit friends
Another basic python question from me.
If I have a working piece of code but if I want to put a part of it in a function I start getting errors like:
UnboundLocalError: Local variable '...' referenced before assignment.
So there has to be something I don´t understand about functions and variable assignment.
Here is an example.
def SelectSheets():
ops = {}
AllSheets = []
AllSheets.extend([MyOptionSheet(x) for x in Sheets if not x.IsPlaceholder])
ops['0_All'] = AllSheets
for SheetSetName, SheetsBySheetSet in zip(SheetSetNames,SheetsBySheetSet):
sheets = []
for Sheet in SheetsBySheetSet:
sheets.append(MyOptionSheet(Sheet))
ops[SheetSetName] = sheets
if OpenSheets:
selectedSheet = forms.SelectFromList.show(ops, 'Print Sheets PDF', group_selector_title='Sheet Sets', default_group= '0_Open', multiselect=False)
else:
selectedSheet = forms.SelectFromList.show(ops, 'Print Sheets PDF', group_selector_title='Sheet Sets', default_group= '0_All', multiselect=False)
return selectedSheet
BrowserSortParameter = BrowserSortParameter()
OpenSheets = OpenSheets()
Sheets = Sheets()
SheetSetNames = SheetSetNames()
SheetsBySheetSet = SheetsBySheetSet()
SheetSetNames, SheetsBySheetSet = AddOpenSheets()
if viewports or ViewportFromSectionLine:
selectedSheet = SelectSheets()
This gives me the error:
UnboundLocalError: Local variable 'SheetsBySheetSet' referenced before assignment.
So the function SelectSheets() recognizes the parameter SheetSetNames without a problem, but it freaks out because it doesn’t know the variable SheetsBySheetSet.
I can make it work by sending the required variable to the function like this:
def SelectSheets(SheetsBySheetSet):
.........
if viewports or ViewportFromSectionLine:
selectedSheet = SelectSheets(SheetsBySheetSet)
So what am I missing here, why does it work for some variables and not for others?
Would be great if someone could explain why this happens.
I know that a variable that is defined in a function dies with the function, but I dont understand why I cant reference a variable that has been defined outside the function before the function was called.
Kind Regards