简体   繁体   中英

Can't figure out UnboundLocalError in Python

The code block, embedded in a function:

try:
    os.makedirs(os.path.dirname(log))
except OSError:
    pass

The error:

UnboundLocalError: local variable 'OSError' referenced before assignment

What could this possibly be a symptom of?

There's an unfortunate source of confusion in the Python 2 exception-catching syntax. Somewhere in the function, you did something like the following:

except SomeError, OSError:

That looks like it's catching two exception types, but it's not. OSError is actually interpreted as the name of the variable you want to hold the SomeError instance you're catching. That means when you try to catch OSError :

except OSError:

OSError refers to the local variable you didn't realize you created.

To catch multiple exception types, you need to parenthesize the list of types to catch:

except (SomeError, OSError):

Your code assigns to OSError somewhere in the function, which means that the compiler has marked it as a local variable. Verify every bit of code where that name shows up to verify that you aren't using it incorrectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM