I'm working on a function that is supposed to return multiple values, which I then unpack into several variables. However, I keep getting the "TypeError: cannot unpack non-iterable NoneType object" error. It seems to happen randomly during execution. Does this mean my function is failing to return the expected tuple, and how can I debug whether the issue is within the function logic itself or the way I am calling it in my script?
3 answers
This error occurs when you try to unpack values from a function call, like x, y = my_function(), but my_function() returns None. In Python, if a function reaches the end without an explicit return statement, or hits a return path that doesn't specify a value, it defaults to None. You should check your function’s conditional logic to ensure every possible path returns a tuple or list. For example, if you have an if statement but no else to handle the alternative, the function will return None when the condition is false, triggering this crash.
Are you using any third-party APIs or database calls inside that function that might be returning a null result, which in turn causes your function to exit prematurely without returning your expected variables?
You should check if the function is actually hitting a return statement. If your code skips all the returns, Python sends back None, and you can't unpack that into variables.
I agree with Donna. I usually add a print statement or use a debugger right before the return to see exactly what the function is passing back. It's the fastest way to find the "None" culprit.
That’s a sharp observation, Brian. I am actually querying a dictionary. If the key isn't found, I'm using .get(), which returns None by default. Should I provide a default empty tuple like (None, None) in the .get() method to prevent the unpacking error, or is it better to wrap the entire function call in a try-except block to catch the TypeError before it stops the program?