This code runs without errors. But in the function find_available_filenumber
the variable render_folder
isn't declared. So my question is why this doesn't produce an error?
If I remove full_filename
as a parameter, I get the error:
UnboundLocalError: local variable 'full_filename' referenced before assignment.
I don't understand why this doesn't also happen with render_folder
, in my code example below:
import bpy
import os
#Functions
def find_available_filenumber(full_filename):
file_number = 1
while os.path.exists(render_folder + "\\" + full_filename):
file_number += 1
full_filename = create_full_filename(filename, file_number)
return file_number
def create_full_filename(filename, file_number):
file_extension = ".avi"
full_filename = filename + "_" + str(file_number) + file_extension
return full_filename
#Paths and names
project_folder = "F:\\06_MotionPath_Dev\\"
os.chdir(project_folder)
render_folder = "Render\\QuickRenderAddon"
filename = bpy.context.scene.name #Returns "QuickRenderAddon"
full_filename = create_full_filename(filename, 1)
filepath = render_folder + "\\" + full_filename
available_number = find_available_filenumber(full_filename)
print("Avail nmb: " + str(available_number))
This is because
render_folder
is declared at the timefind_available_filenumber
is called, even though its not declared when your function is defined.Ah yes the classic "Referenced before Assignment"
I wrote some example code to show what is going on.
The output of the above is
This shows that we can read global variables, but what about writing to them? I don't want 'toast' to be 'test!' anymore, but rather 'bread+toaster!'. Let's write this out.
This outputs
You'll notice that we were able to print the locally assigned variable, but the global variable did not change. Now, let's look at another example.
This will throw the error
Why? Because you're later declaring your variable 'toast' as a local variable. Python notices this and stops the code to prevent errors. You setting 'toast' later is not changing the global variable, but rather declaring a local one within the function called 'toast'.
How can you fix this?
The first would be to add a global clause inside your function
This outputs
You can also modify your code into a class structure, as such.
In my opinion, classes are the best solution as it will increase modularity and help you reduce spaghetti code.
Edit: Ignore me, I'm on mobile, so I didn't properly read.
The error states "referenced before assignment". In other words, you are trying to read a value from that variable before you have written a value to it.
I have a feeling this error is being cause in your while conditional, as you are checking the value before writing to it in the body of the while loop.