3

What, if anything, is wrong with this line of python code:

daterange = [begin + timedelta(n) for n in range((end - begin).days)]

Where begin and end are datetime.date objects with valid values.

I'm using this in a Django view to process some data, but everytime the view this is in gets called I get the following error with the aforementioned line highlighted:

UnboundLocalError at /url/of/error/creating/view/here/
local variable 'range' referenced before assignment

If I execute this line inside the interpreter it works fine, but somehow it doesn't fly inside a Django view. I don't understand why range is being interpreted as a variable name at all. Is there actually something wrong with this line, or is it something else in the code that's making Django complain?

Help!

chandsie
  • 2,865
  • 3
  • 27
  • 37

1 Answers1

11

There's nothing wrong with Django. You create a local variable range in the same scope (by assigning one). For instance range = None in the very last line of a function makes Python consider an occurrence of range in the first line of the same function a reference to that local variable. Since it doesn't have a value assigned at that point, you get an UnboundLocalError.

  • I'm not quite sure I follow what you're saying as I don't have any explicit variables name range anywhere in that method, or for that matter in the entire file. – chandsie Apr 22 '11 at 21:54
  • @chands: Well, you *must* have one somewhere, or it wouldn't consider it a local variable. Show the source (of the method only). –  Apr 22 '11 at 21:55
  • Ahh crud. You're right. I had a misspelled variable name later in the method. My fault! – chandsie Apr 22 '11 at 21:59
  • this is a very confusing point for new programmers. It is big gotcha that I have encountered alot. – Garrett Berg Apr 23 '11 at 04:54
  • why the word is not reserved as a statement? – Enrico Ferreguti Feb 10 '17 at 21:13