Question

Check out the following piece of code.

I get a UnboundLocalError: "local variable 'os' referenced before assignment" error at the if statement.

I set a pdb trace right there, and I tried to check out the os module.

import os
import pdb

... 

pdb.set_trace()

if not os.path.exists(path_to_temp):
    os.makedirs(path_to_temp)

Here's my bizarre interaction in pdb:

(Pdb) os.path.exists(path_to_temp)
False
(Pdb)  not os.path.exists(path_to_temp)
True
(Pdb) os.path
<module 'posixpath' from '/usr/lib/python2.7/posixpath.pyc'>
(Pdb) os
<module 'os' from '/usr/lib/python2.7/os.pyc'>
(Pdb) n
UnboundLocalError: "local variable 'os' referenced before assignment"

I don't even...

EDIT: Omg, shame on me. I had a local import os somewhere after this if-statement too!!

Was it helpful?

Solution

Turns out I had a local import os after this if-statement, which was affecting the os attribute for the scope of that function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top