Ad

Python Modules (modulename Referenced Before Assignment)

- 1 answer

I have a vm.py in the same directory as the main() script (getdata.py). In getdata.py, I have

import vm
...
x = vm.Something()

Then python complains

UnboundLocalError: local variable 'vm' referenced before assignment

Why is that? There was no error when importing.

UPDATE

I found that if I did

from vm import * 

Instead it worked. Also for another file/module I made, a simple import works. I uploaded the full code to GitHub Gist https://gist.github.com/2259298

Ad

Answer

Inside your main function, you had a line vm = VirtualMemory(args['numFrames'], algo). The result of this is that Python recognises vm as a local variable inside the function, and so when you try to access vm, meaning the vm module, before having assigned a value to it locally, it complains that you haven't assigned a value to it.

The upshot of it is that you should rename either your variable vm or your module vm to something else.

(One last thing: avoid from X import * statements, they make debugging hard; list what you're importing explicitly. You don't want to import names like main, anyway.)

Ad
source: stackoverflow.com
Ad