Basic Python: Exception raising and local variable scope / binding

Posted by SuperJdynamite on Stack Overflow See other posts from Stack Overflow or by SuperJdynamite
Published on 2010-04-30T13:32:19Z Indexed on 2010/04/30 13:37 UTC
Read the original article Hit count: 206

I have a basic "best practices" Python question. I see that there are already StackOverflow answers tangentially related to this question but they're mired in complicated examples or involve multiple factors.

Given this code:

#!/usr/bin/python

def test_function():
   try:
      a = str(5)
      raise
      b = str(6)
   except:
      print b

test_function()

what is the best way to avoid the inevitable "UnboundLocalError: local variable 'b' referenced before assignment" that I'm going to get in the exception handler?

Does python have an elegant way to handle this? If not, what about an inelegant way? In a complicated function I'd prefer to avoid testing the existence of every local variable before I, for example, printed debug information about them.

© Stack Overflow or respective owner

Related posts about python

Related posts about exception-handling