Local Variable Referenced Before Assignment Xbmchub

I know this has been asked before because I've searched around for an answer but the questions that I've read through don't really address my problem. I wrote a river warning system using Python3. Initially the script would only retrieve the data for the river closest to my house, so I decided to do a re-write or version upgrade, I suppose, so that any river could be used. Everything has been working pretty nice until I entered the Mississippi river URL and then I started getting

UnboundLocalError: local variable 'action' referenced before assignment.

Here is the code:

EDIT - Added the entire function to show where is defined

so then when I execute the function here are the results:

I've moved the variables around the appropriate and blocks but that doesn't seem to help. I've tried assigning them as variables as mentioned here. I've also gone back over the URL data from water.weather.gov and compared each river stage/flood alerts and it all appears to be the same for each river. So now I'm just confused as to why the variable 'action' is referenced before assignment in the Mississippi river data when it's not in the first three.


This is because, even though exists, you're also using an assignment statement on the name inside of the function ( at the bottom line). Naturally, this creates a variable inside the function's scope called (truthfully, a or will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:

inside the top of your function. This will tell Python that you don't intend to define a or variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.

Some Resources

  • the Python website has a great explanation for this common issue.
  • Python 3 offers a related statement - check that out as well.

0 Replies to “Local Variable Referenced Before Assignment Xbmchub”

Lascia un Commento

L'indirizzo email non verrĂ  pubblicato. I campi obbligatori sono contrassegnati *