Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Modules (modulename referenced before assignment)

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

like image 461
Jiew Meng Avatar asked Feb 20 '23 23:02

Jiew Meng


1 Answers

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.)

like image 195
Chris Morgan Avatar answered Mar 03 '23 21:03

Chris Morgan