Fix flags variable being set

If an exception is raised, this is thrown:

UnboundLocalError: local variable 'flags' referenced before assignment