4

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

jamylak
  • 128,818
  • 30
  • 231
  • 230
Jiew Meng
  • 84,767
  • 185
  • 495
  • 805
  • 1
    By itself, that should work. Probably there are other references to vm in your code which you cut out in the `...` part because you didn't think they were relevant, but really they were. See, e.g., [this question](http://stackoverflow.com/questions/1188944/reason-for-unintuitive-unboundlocalerror-behaviour), or [this one](http://stackoverflow.com/questions/404534/python-globals-locals-and-unboundlocalerror). – DSM Mar 31 '12 at 04:10
  • @DSM, updated post with observations and full code on gist (https://gist.github.com/2259298) – Jiew Meng Mar 31 '12 at 04:34
  • Command line arguments are never done in camel case; `--numReferences` would be typically done as `--num-references` or `--references`. – Chris Morgan Mar 31 '12 at 04:46

1 Answers1

8

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

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215